Python Dictionary
Python Dictionary
[1]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
[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
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)
[6]: print(len(thisdict))
[7]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
<class 'dict'>
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Mustang
[10]: 1964
2
[11]: # The keys() method will return a list of all the keys in the dictionary.
thisdict.keys()
[12]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"yr" : 1964
}
x = car.keys()
car["color"] = "white"
[13]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"yr" : 1964
}
print(car)
[ ]: #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()
3
car["year"] = 2020
[ ]: # 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")