python-dictionary
October 23, 2024
[1]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
[3]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
print(thisdict["year"])
Ford
1964
Ordered or Unordered? As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.
Unordered means that the items do not have a defined order, you cannot refer to an item by using
an index.
[4]: my_dict = {}
my_dict['a'] = 1
my_dict['b'] = 2
my_dict['c'] = 3
my_dict['d'] = 4
my_dict
[4]: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Duplicates Not Allowed Dictionaries cannot have two items with the same key:
1
[5]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2024
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2024}
[6]: print(len(thisdict))
[7]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
<class 'dict'>
[8]: #The dict() Constructor
#It is also possible to use the dict() constructor to make a dictionary.
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
{'name': 'John', 'age': 36, 'country': 'Norway'}
[9]: #Accessing Items
#You can access the items of a dictionary by referring to its key name, inside␣
↪square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Mustang
[10]: # by using get()
thisdict.get("year")
[10]: 1964
2
[11]: # The keys() method will return a list of all the keys in the dictionary.
thisdict.keys()
[11]: dict_keys(['brand', 'model', 'year'])
[12]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"yr" : 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
[13]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"yr" : 1964
}
print(car)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'yr': 1964}
[ ]: #The values() method will return a list of all the values in the dictionary.
x = thisdict.values()
print(x)
[ ]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
3
car["year"] = 2020
print(x) #after the change
[ ]: # The items() method will return each item in a dictionary, as tuples in a list.
x = thisdict.items()
print(x)
[ ]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")