Operations and Usage of Dictionary - Python


Dictionary is one of the data-type(data-structure) in python.
It store's the data in a hash-map format(keys, values)

How to create a dictionary ?

d = dict()
print(d)
Output: {}
# otherway
d = {}
print(d)
# Output: {}
# with default values
d = dict([("ten", 10), ("twenty", 20)])
print(d)
# Output: {'ten': 10, 'twenty': 20}
# or you can directly
d = {'ten': 10, 'twenty': 20}
print(d)
#Output: {'ten': 10, 'twenty': 20}

How to insert values into dictionary ?

d = {"ten": 10}
# insert
d["twenty"] = 20
print(d)
# Output: {'ten': 10, 'twenty': 20}

How to access values from dictionary ?

d = {'ten': 10, 'twenty': 20}
# case1:
data = d["ten"]
print(data)
# Output: 10
# access with no key
d["thirty"]
KeyError: 'thirty'
# case2
data = d.get("ten")
print(data)
# Output: 10
# no key
data = d.get("thirty")
print(data)
Output: None

How to delete a key from dictionary ?

# case1 with "del"
d = {'ten': 10, 'twenty': 20}
del d["ten"]
print d
# Output: {'twenty': 20}
# no key found
del d["five"]
# Output: KeyError: 'five'
#case2 with pop
d = {'ten': 10, 'twenty': 20}
val = d.pop("ten")
print d
# Output: {'twenty': 20}
print val
# Output: 10
# no key found
d = {'ten': 10, 'twenty': 20}
val = d.pop("ten")
print d
# Output: {'twenty': 20}
print val
# Output: 10
val = d.pop("five", None)
print val
# Output: None

How to update dictionary with other dictionary ?

d1 = {"ten": 10, "twenty": 20}
d2 = {"thirty": 30, "forty": 40}
d1.update(d2)
# Output: {'forty': 40, 'ten': 10, 'thirty': 30, 'twenty': 20}
print d1
# Output: {'forty': 40, 'thirty': 30}

How to check whether the dictionary has a key or not ?

d = {'forty': 40, 'ten': 10, 'thirty': 30, 'twenty': 20}
print d.has_key("ten")
# Output: True
print d.has_key("fifty")
# Output: False

How to get all keys from a dictionary ?

print d.keys()
# Output: ['thirty', 'forty', 'ten', 'twenty']

How to get all values from a dictionary ?

print d.values()
# Output: [30, 40, 10, 20]

How to empty/clear the dictionary?

d = {'forty': 40, 'ten': 10, 'thirty': 30, 'twenty': 20}
print d
# Output: {'forty': 40, 'ten': 10, 'thirty': 30, 'twenty': 20}
d.clear()
print d
# Output: {}

How to copy a dictionary?

d1 = {'forty': 40, 'ten': 10}
d2 = d1.copy()
print "memory id of d1: ", id(d1)
# Output: memory id of d1: 140210110002072
print d1
# Output: {'forty': 40, 'ten': 10}
print "memory id of d2: ", id(d2)
# Output: memory id of d2: 140210109733976
print d2
# Output: {'forty': 40, 'ten': 10}

How to get list of key, value pairs from a dict ?

d1 = {'forty': 40, 'ten': 10}
l = d1.items()
print l
# Output: [('forty', 40), ('ten', 10)]

If you want to learn more visit: https://docs.python.org/2/tutorial/datastructures.html#dictionaries

Buy a product to Support me