Python Dictionary

In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary.

# Create a new dictionary 
d = dict() # or d = {}

# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345

# print the whole dictionary

# print only the keys

# print only values

# iterate over dictionary 
for i in d :
    print("%s  %d" %(i, d[i]))

# another method of iteration
for index, value in enumerate(d):
    print (index, value , d[value])

# check if key exist
print('xyz' in d)

# delete the key-value pair
del d['xyz']

# check again 
print("xyz" in d)


{'xyz': 123, 'abc': 345}
['xyz', 'abc']
[123, 345]
xyz 123
abc 345
0 xyz 123
1 abc 345

Dictionary Programs, Built-in Functions

Built-in Functions

  • Dict.cmp(): Compares elements of both dict.
  • Dict.len(): Gives the total length of the dictionary.
  • Dict.str(): Produces a printable string representation of a dictionary.
  • Dict.type(): Returns the type of the passed variable.
  • Dict.clear(): Removes all elements of dictionary dict
  • Dict.copy(): Returns a shallow copy of dictionary dict
  • Dict.fromkeys(): Create a new dictionary with keys from seq and values set to value.
  • Dict.get(): For key, returns value or default if key not in dictionary
  • Dict.has_key(): Returns true if key in dictionary dict, false otherwise
  • Dict.items(): Returns a list of dict’s (key, value) tuple pairs
  • Dict.keys(): Returns list of dictionary dict’s keys
  • Dict.setdefault(): Set dict[key]=default if key is not already in dict
  • Dict.update(): Adds dictionary dict2’s key-values pairs to dict
  • Dict.values(): Returns list of dictionary dict’s values

Dictionary Programs

Useful Links

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:

0 Average Difficulty : 0/5.0
No votes yet.