L

learnasyoulike

time


Python Dictionaries

Table of contents:

Python Dictionaries

A python dictionary is a collection object which allows to store data in comma-separated key-value pairs. A key in dictionary is an identifier and a value is associated with a key.

A dictionary is enclosed inside a pair of curly braces. The keys and values are separated with colons (:) as in the following:

{"name": "Arka", "age": 13, "roll": 10}

In the above, "name", "age" and "roll" are dictionary keys, while "Arka", 13 and 10 are dictionary values.


Table of contents:

The {} Create dictionary with curly braces

We can create a new dictionary by enclosing key-value pairs inside a pair curly braces.

Here, the key "name" represents the value "Arka", the key "age" represents the value 13, and the key "roll" represents the value 10.

An empty dictionary can be defined with curly braces:

Length of a dictionary: len() function

Python len() function can be used to find the length of an object. When the argument is a dictionary object, len(dictionary) simply returns the length of the given dictionary. In other words, the number of key-value pairs in the dictionary is returned.

An empty dictionary has a zero length. Note that the data-type of variable length is 'int'.

Function dict() - Create a dictionary

An empty dictionary can also be defined with the dict() function:


The dict() function accepts multiple tuples inside a list. In that case, we have to enclose the keys and values inside tuples with commas.

Since dict() function accepts only one argument, we have to enclose the tuples inside a list or tuple.

Observe the following python commands, though they are different in syntax, all of them return the same output.

In fact, all the above will return the same output
{'name': 'Arka', 'age': 13, 'roll': 10}

The dict() function dict( [ ("P", 111), ("Q", 222), ("R", 333) ] ) key value one set of data * one dictionary * This should be enclosed inside a list or tuple Because dict() accepts one argument only

Output of the above call will be a dictionary:
{'P': 111, 'Q': 222, 'R': 333}

If the keys of a dictionary are simple strings, we can define the dictionary as follows:

If the data-type of the keys is not 'str', the above method won't work.

Access a value from dictionary

We can access a value from an existing dictionary by specifying the respective key in square brackets. For example, in the above dictionary d2,

This looks like accessing items from a python list, though this is not indexing. The square-bracket notation is very important and frquently used to access, modify and add new key-value pairs to a dictionary.

In the above dictionary d3,

If the given key is not found in the specified dictionary, a KeyError will be raised by python.
A value can be accessed from a dictionary with the .get() method too.

Add new key-value pair to dictionary

We can add new key-value pairs to an existing dictionary by using the same square-bracket notation in an assignment statement.

In the above, a new key "S" and its value "Sulfur" have been added to dictionary d4.

In the following, we add new keys and values to an empty dictionary.

Modify the value of a key

We can modify the value of a key in the same way:

Remember that if the specified key is not in the dictionary, it will be appended alongwith the value as a new pair of data.

Properties of a dictionary


Dictionaries are ordered

Dictionaries are ordered since version 3.7. Python remembers the order of the key-value pairs in which they were entered and maintains this order while displaying the dictionary. But dictionary keys or values have no index.



Dictionaries are mutable

Dictionaries are mutable objects in the sense that we can any time add, modify or remove a key-value pair to and from a dictionary.



Dictionaries keys are unique

In a dictionary, a key cannot appear multiple times. Even if we enter a key more than once, the last key-value pair will be accepted. However, a value can appear multiple times, and it can be of any type.

Here, only the last key-value pair "b": 1 is accepted.



Dictionaries keys must be immutable

This is most important. Dictionary keys must be immutable objects like integer, float, boolean, string, tuple, even a None.

Here, the first key 2 is of 'int' type, the second key 3.14 is of 'float' type.
It is important to note that mydict[2] is not indexing, and the 2 here is not an index, it is a key of the dictionary mydict. Python dictionaries do not support indexing.


Here, the first key True is of 'bool' type, the second key None is of 'NoneType' type.


A python tuple, being immutable, can be a key of a dictionary.

Attention! The tuple we use as a key of a dictionary should not contain any mutable item. (1, 2, [9]) is an invalid key for a dictionary, though it is a valid tuple.

The following are invalid as dictionary keys, but they are valid tuples.



Dictionaries values can be of any type

A value in a dictionary can be of any type.

Membership with dictionary

Python membership operators in and not in can be used to check whether a key occurs in a dictionary or not.


Since the key "Maths" is present in subjects, the membership expression "Maths" in subjects returns a True. "Science" is also a key of the dictionary subjects, so the expression "Science" not in subjects returns a False.

Dictionary methods


Method dictionary.update() - Merging dictionaries

The .update(dictionary/iterable) method accepts only one argument, either a dictionary or an iterable. It merges the original dictionary with the dictionary or iterable in the given argument. This method does not return any new dictionary, but modifies the original one(dict1 in the following).


dict1 (original dictionary) is updated with the merged result of dict1 and dict2.


If any of the key of the original dictionary is found in the dictionary/iterable in the argument, then the value of that key will be updated in the original dictionary.

Since the key "a" is present in both the dictionaries, the old value "ant" is replaced with the new value "ass" in the original dictionary.


The .update() method can accept an iterable.

Method dictionary.pop() - Remove a key-value pair

The .pop(key [, default-value]) method accepts a key, removes the key and its value, and returns the deleted value. If the given key is not found in the dictionary, python raises a KeyError.


We can optionally pass a default value as a second argument to .pop() method. If the specified key is not found, this value is returned, and python raises no error.


Note that there is no "z" key, so no key is deleted. dict1.pop("z", "default_value") returns 'default_value', because we passed a default value as a second argument. Because of the second argument, no error is raised.

Method dictionary.popitem() - Remove the last key-value pair

The .popitem() method removes the last key-value pair, and returns the deleted key and value in a tuple. If the dictionary is empty, python raises a KeyError.


Removing the last key-value pair is possible because dictionaries are ordered. This method accepts no parameters.

Method dictionary.get() - Access a value

The dict.get(key [, default-value]) method accepts a key, and returns the value of that key. If the given key is not found in the dictionary, python returns a None and raises no error.


This method is handy when we do not know if a key exists or not.

We can optionally pass a value as a second argument to .get() method. If the specified key is not found, this value is returned.


Observe that dict1.get("d") returns nothing, because the key "d" is not found. But dict1.get("d", "somevalue") returns 'somevalue', because we passed a default value as a second argument.

Method dictionary.keys() - Access all the keys

The .keys() method returns a list of all the keys in the dictionary. It accepts no parameters.


The .keys() method retuns an object of data-type 'dict_keys' as above.
If we want a simple list of the keys, we can use the list() function and pass the .keys() method as an argument to the list() function.

Method dictionary.values() - Access all the values

The .values() method returns a list of all the values in the dictionary. Like .keys() method, it also returns an object of data-type 'dict_values'. This method accepts no parameters.

Method dictionary.items() - Access all the key-value pairs

The .items() method returns a list of all the keys and values contained in tuples. Like .keys() method, it also returns an object of data-type 'dict_items'. This method accepts no parameters.

Method dictionary.copy() - Copies a dictionary

The .copy() method copies a dictionary. This method accepts no parameters.

We can also copy a dictionary by assignment method dict1 = dict2 where both the dictionaries will point to the same object. In that case, if we modify dict1, then dict2 will also get modified, and vice versa. But in the above, dict1 and dict2 point to two different objects; you can check this with the python is operator .

Method dictionary.clear() - Remove all key-value pairs

The .clear() method removes all the key-value pairs from a dictionary. This method accepts no parameters.

Method dict.setdefault()

The dict.setdefault(key [, value]) method accepts a key, and optionally a value. If the given key is in the dictionary, its value is returned. In this case if we pass a value, it will be ignored.

If the given key is not in the dictionary, the key-value pair will be appended, and the value will be returned. In this case if we do not pass a value, it will be a None.

Method dict.fromkeys() - Create dictionary from an iterable

The dict.fromkeys(iterable[, value]) method accepts an iterable, and optionally a value. It creates a new dictionary with the keys from the given iterable. All the values will be set to the given value. If the second argument value is not given, a None is used.


The following format may also be used.





--- x ---









Want to leave a message for me?