Dictionaries in Python

0
240
Dictionaries in Python
Dictionaries in Python

A dictionary in Python is a mutable and unordered sequence of elements. Like lists, dictionaries in Python are built-in data structures. Python dictionaries are indexed by keys, which can be any immutable type. Each item that is contained in a dictionary is a key: value pair. Keys within one dictionary must be unique.

1. Creating a Dictionary in Python

A Python dictionary is created by specifying a set of key: value pairs inside curly brackets { }.

>>> person = {} # Creating an empty dictionary
>>> print(person)
{}
>>> person = {"name": "Tom", "gender": "M"} # Creating a dictionary with two key: value pairs
>>> print(person)
{'name': 'Tom', 'gender': 'M'}

A dictionary can also be created from sequences of key-value pairs using the dict() constructor as shown below:

>>> details = [("name", "Tom"), ("age", 30), ("gender", "M")]
>>> person = dict(details)
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}

2. Accessing Items of a Dictionary

Items of a dictionary can be accessed by referring to its key name inside square brackets. Using a non-existent key produces an error.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person["name"])
Tom
>>> print(person["address"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'address'

3. Modifying Values

The value of a specific item of a dictionary can be changed by referring to its key name.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> person["age"] = 40
>>> print(person)
{'name': 'Tom', 'age': 40, 'gender': 'M'}

4. Checking Key Existence Using the ‘in’ Keyword

The ‘in’ keyword can be used to check if a specified key exists in a dictionary.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print ("gender" in person)
True
>>> print ("address" in person)
False

5. Length of a Dictionary

The len() method can be used to check how many items (key-value pairs) a dictionary contains.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print (len(person))
3

6. Adding an Item to a Dictionary

An item can be added to a dictionary by using a new key and assigning a value to it.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> person["address"] = "123 Street"
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M', 'address': '123 Street'}

7. Removing an Item from a Dictionary

An item can be removed from a dictionary using the ‘del’ keyword.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> del person["age"]
>>> print(person)
{'name': 'Tom', 'gender': 'M'}

It is also possible to delete the dictionary completely using the del keyword.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> del person
>>> print(person)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'person' is not defined

8. Dictionary Methods

Like other data structures, dictionaries in Python also support some built-in methods to perform common operations. Some of the most commonly used methods are given below:

dict.keys()

It returns a view object containing the keys of the dictionary as a list.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.keys())
dict_keys(['name', 'age', 'gender'])

dict.values()

It returns a view object containing the values of the dictionary as a list.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.values())
dict_values(['Tom', 30, 'M'])

dict.items()

It returns a view object containing the key-value pairs of the dictionary as tuples in a list.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.items())
dict_items([('name', 'Tom'), ('age', 30), ('gender', 'M')])

dict.get()

It returns the value of the item with the specified key.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.get("gender"))
M

It is possible to specify an optional value as the second argument to this method. If specified, this value is returned if the specified key does not exist.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.get("address"))
None
>>> print(person.get("address", "Not Specified"))
Not Specified

dict.pop()

It removes the item with the specified key from the dictionary. The value of the removed item is the return value of this method.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.pop("age"))
30
>>> print(person)
{'name': 'Tom', 'gender': 'M'}
>>> print(person.pop("address"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'address'

It is possible to specify an optional value as the second argument to this method. If specified, this value is returned if the specified key does not exist.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.pop("address", "NA"))
NA

dict.popitem()

It removes the item that was last inserted into the dictionary. This method returns the removed item as a tuple.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> person["address"] = "123 Street"
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M', 'address': '123 Street'}
>>> print(person.popitem())
('address', '123 Street')
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}

dict.clear()

It removes all the items from a dictionary.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> person.clear()
>>> print(person)
{}

dict.copy()

It returns a copy of the specified dictionary.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> employee = person.copy()
>>> print(employee)
{'name': 'Tom', 'age': 30, 'gender': 'M'}

dict.fromkeys()

It returns a dictionary with the specified keys and values. The first argument to this method is required and is an iterable specifying the keys of the new dictionary. The second argument is optional and is the value for all keys of the new dictionary. If the second argument is not specified, all keys of the new dictionary have a default value ‘None’.

>>> details = ["name", "age", "gender"]
>>> person = dict.fromkeys(details)
>>> print(person)
{'name': None, 'age': None, 'gender': None}
>>> details = ["name", "age", "gender"]
>>> value = "NA"
>>> person = dict.fromkeys(details, value)
>>> print(person)
{'name': 'NA', 'age': 'NA', 'gender': 'NA'}

dict.setdefault()

It returns the value of the item with the specified key. If the specified key does not exist in the dictionary, this method inserts the key with the specified value.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.setdefault("gender", "NA"))
M
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> print(person.setdefault("address", "NA"))
NA
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M', 'address': 'NA'}

dict.update()

It inserts the specified items into the dictionary. The specified items can be a dictionary or an iterable object with key-value pairs.

>>> person = {"name": "Tom", "age": 30, "gender": "M"}
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M'}
>>> new_items = {"address": "123 Street", "designation": "graphic designer"}
>>> person.update(new_items)
>>> print(person)
{'name': 'Tom', 'age': 30, 'gender': 'M', 'address': '123 Street', 'designation': 'graphic designer'}
Dictionaries in Python
5 (100%) 3 vote[s]

SHARE
Previous articleLists in Python