DICTIONARIES
A dictionary is a mapping of keys to values. Itโs also sometimes called a hash table or associative array. The keys serve as indices for accessing values. Dictionaries are written with curly brackets as shown in the below examples.
Dictionaries in python are used to store data values in key: value pairs each pair is separated by a comma and all pairs are enclosed in curly brackets.
A dictionary in python is a collection that is ordered, changeable, and does not allow duplicates.
Dictionaries in python are ordered, which means that the items have a defined order, and that order will not change.
Dictionaries in python are changeable, meaning that we can change, add or remove items after the dictionary has been created.
Dictionaries in python donโt allow duplicates, meaning that we cannot have two items with the same key.
s = {
'name': 'GOOG',
'shares': 100,
'price': 490.1
}
COMMON OPERATIONS
HOW TO ACCESS VALUES FROM A DICTIONARY?
Use the key names.
>>> print(s['name'], s['shares'])
GOOG 100
>>> s['price']
490.10
>>>
Use the get() method.
>>> x=s.get('name')
Use the keys() function to get the list of all keys in the dictionary.
>>> x=s.keys()
HOW TO ACCESS ITEMS FROM A DICTIONARY?
Use the items() function.
It will return each item in a dictionary, as tuples in a list.
>>> x=s.items()
HOW TO ADD OR MODIFY VALUES IN DICTIONARY?
Assign values using the key names.
>>> s['shares'] = 75
>>> s['date'] = '6/6/2007'
>>>
Use update() function
The update() function will update the dictionary with the items from the given argument. The argument must be a dictionary, or an iterable object with key:value pairs.
s = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
s.update({"year": 2020})
HOW TO DELETE A VALUE IN DICTIONARY?
Use the del statement.
>>> del s['date']
>>>
HOW TO DETERMINE THE LENGTH OF DICTIONARY?
Use the len function
>>> print(len(s))
>>>
WHAT IS THE DATA TYPE OF ITEMS IN THE DICTIONARY?
The values in dictionary items can be of any data type.
Dictionaries are defined as objects with the data type โdictโ.
Use the type function to identify the data type of the dictionary object.
Example
>>> print(type(s))
HOW TO MAKE DICTIONARY OBJECT USING A CONSTRUCTOR?
Use the dict() function as Constructor โ
>>> a = dict(name = "Jonny", age = 38, country = "India")
>>> print(a)
HOW TO CHECK IF A SPECIFIED KEY IS PRESENT IN A DICTIONARY?
Use the in keyword-
s = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in s:
print("Yes, 'model' is one of the keys in the s dictionary")
Why dictionaries?
Dictionaries are useful when there are many different values and those values might be modified or manipulated. Dictionaries make your code more readable.
s['price']
# vs
s[2]
Leave a Reply