5. Data Structures (Part 2) - MantsSk/CA_PTUA14 GitHub Wiki
Dictionary
A very powerful data structure which is going to be used a lot. Dictionary
hold key: value pairs, with which we can access it's attributes.
Dictionaries are:
- mutable ✔️ (can be changed)
- dynamic ✔️ (can grow and shrink in size)
- nested ✔️ (can contain other dictionaries or other complex structures)
A dictionary
is a collection which is ordered, changeable and do not allow duplicates.
Main difference between python list
and dictionary
is that values in dictionaries are accessed by keys.
Creating a dictionary and adding values to it is as simple as:
my_dictionary = {}
my_dictionary["name"] = "Tom"
print(my_dictionary["name"])
my_dictionary = {"name": "Tom"}
print(my_dictionary["name"])
Access dictionary values
my_dictionary = {"name": "Tom", "surname": "Edison"}
print(f"name: {my_dictionary['name']}")
print(f"surname: {my_dictionary['surname']}")
If the value is non existent
we shall get a KeyError
as such key
does not exist:
my_dictionary = {"name": "Tom", "surname": "Edison"}
print(f"favourite car: {my_dictionary['car']}")
# KeyError: 'car'
Dictionaries may use any immutable type
as it's key
(so no list
as for example) and any type as its values
:
values
in dictionary
Changing my_dictionary = {"name": "Tom", "surname": "Edison"}
my_dictionary["name"] = "Charles"
print(f"name: {my_dictionary["name"]}")
key
from dictionary
Droping my_dictionary = {"name": "Tom", "surname": "Edison"}
del my_dictionary ["name"]
print(my_dictionary)
nested
structures
More complex, As with the lists
, we have seen that lists can contain other lists
, it so happens that the dictionary can have a value of another diciotnary
and we can built a complex hierarchies like that:
user_info = {
"name": "Albert",
"surname": "Einstein",
"occupation": {
"role": "Professor",
"workplace": "University of Berlin"
},
"languages": ["German", "Latin", "Italian", "English", "French"]
}
Let's say we wanted to print all the languages one by one, we could do something like this:
user_info = {
"name": "Albert",
"surname": "Einstein",
"occupation": {
"role": "Professor",
"workplace": "University of Berlin"
},
"languages": ["German", "Latin", "Italian", "English", "French"]
}
for language in user_info["languages"]:
print(language)
The possibilities are almost endless, we can go deeper and deeper.
.items()
There will be many of situations, that we will want to iterate through dictionary
. We will be using in-built .items()
method for dictionaries
.
d = {'a': 10, 'b': 20, 'c': 30}
print(list(d.items()))
.keys()
This method returns dictionary keys:
d = {'a': 10, 'b': 20, 'c': 30}
list(d.keys())
.values()
This method returns dictionary values:
d = {'a': 10, 'b': 20, 'c': 30}
list(d.values())
.pop
This method pops the key value
pair based on key
and returns its value
:
d = {'a': 10, 'b': 20, 'c': 30}
result = d.pop('a')
print(result)
print(d)
.update(obj)
If obj
is a dictionary
, my_dictionary.update(obj)
merges the entries from obj
into dictionary my_dictionary
.
If the key
is not present in a dictionary
my_dictionary
, the key-value
pair from obj
is added to my_dictionary
,
otherwise, the corresponding value in my_dictionary
for that key
is updated with the value
from obj
.
Examples:
dict_one = {'a': 10, 'b': 20, 'c': 30}
dict_two = {'b': 200, 'd': 400}
dict_one .update(dict_two )
print(dict_one )
dict_one = {'a': 10, 'b': 20, 'c': 30}
dict_one .update([('b', 200), ('d', 400)])
print(dict_one )
dict_one = {'a': 10, 'b': 20, 'c': 30}
dict_one .update(b=200, d=400)
print(dict_one )
dictionary
Iterating through Example:
d = {'a': 10, 'b': 20, 'c': 30}
for key, value in d.items():
print(key, value)
lists
into a dictionary
Converting two Note that lists
must be of the same size here:
test_keys = ["Albert", "Tom", "Stephen"]
test_values = [1, 4, 5]
my_dictionary= dict(zip(test_keys, test_values))
print(my_dictionary)
Sets
Sets
are used to store multiple items in a single variable
.
A set
is a collection which is unordered, unchangeable, and unindexed.
Note: Set items are unchangeable, but you can remove items and add new items.
Notation:
my_set = {1, 2, 3}
Another important property is that in sets
we can't store duplicates values:
my_set = {1, 2, 3, 1}
print(my_set)
# {1, 2, 3}
For example, getting unique values from python list
:
numbers_list = [1, 2, 3, 4, 5, 5, 5, 6]
numbers_set = set(numbers_list)
print(numbers_set)
🧠Exercises
-
Write python program that asks user to enter
name
,surname
,age
. Put these values into a dictionary and print it. -
Try creating
nested
dict
structure which would use all data types and structures you already know. -
Create a program, that would take sentences from the
input
and create adictionary
where theykeys
representsword
andvalues
the frequency those words appeared in those sentence. It doesn't matter if the word is upper case or lower case, it sounds like the same word.
Example: Enter a sentence: Hello hello its me, I was wondering about those all years we had been together. You and I.
Output: {'hello': 2, 'its': 1, 'me': 1, 'i': 2, 'was': 1, 'wondering': 1, 'about': 1, 'those': 1, 'all': 1, 'years': 1, 'we': 1, 'had': 1, 'been': 1, 'together': 1, 'you': 1, 'and': 1}