A “dictionary” is a collection which is unordered, mutable & indexed.
In Python, dictionaries are indicated with curly brackets { }, and they have pair of
keys and values.
Why use Dictionary?
In dictionary, we can keep the elements in key-value mapping arrangement.
Internally uses hashing for accessing the key value pair, so we can locate elements using key very quickly.
key : value (pairing)
#creating dictionary and printing content and type
my_dict = {
"id": 1,
"name": "Hello World",
"year": 2020
}
print(my_dict)
print(type(my_dict))
#Output: {'id': 1, 'name': 'Hello World', 'year': 2020}
#<class 'dict'>
Accessing Items
my_dict = {
"id": 1,
"name": "Hello World",
"year": 2020
}
# accessing dictionary key- name
name = my_dict["name"]
print(name)
Accessing Items using get()
my_dict = {
"id": 1,
"name": "Hello World",
"year": 2020
}
# accessing dictionary element
name = my_dict.get("name")
print(name)
Dictionary fromkeys() method
The fromkeys() method creates a new dictionary from the given sequence of elements with a value provided by the user.
x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
#output- ['key1': 0, 'key2': 0, 'key3': 0]
Keys () and values () methods
#The keys and values methods are used to return lists containing the dictionaries keys and values respectively
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
#output- [brand, model, year]
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)
#output- [Ford, Mustang, 1964]