Skip to content

Dictionary in Python

wilsonshamim edited this page Jun 12, 2018 · 1 revision

we create Dictionary as a name value pair in {}.

dict = {"name":“a”,age

Accessing dictionary:
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −
dict = {"name":“a”,age
print(dict[‘name’])
dict[“name”] = “bb”
dict[“sex”] = “m”
print(dict)
{’name’: ‘bb’, ‘age’: 22, ‘sex’: ’m’}

Deleting dictionary:
del dict[‘Name’]; # remove entry with key ‘Name’
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

Properties of Dictionary Keys
1. More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.
2. Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like [‘key’] is not allowed. Following is a simple example −

dict = {[‘Name’]: ‘abc’, ‘Age’: 7}
print "dict[‘Name’]: ", dict[‘Name’]

Python includes following dictionary methods −

Sr.No. Methods with Description
1 dict.clear()
Removes all elements of dictionary dict

2 dict.copy()
Returns a shallow copy of dictionary dict

3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary

5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise

6 dict.items()
Returns a list of dict’s (key, value) tuple pairs

7 dict.keys()
Returns list of dictionary dict’s keys

8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict

9 dict.update(dict2)
Adds dictionary dict2’s key-values pairs to dict

10 dict.values()
Returns list of dictionary dict’s values

Clone this wiki locally