DICTIONARY QUESTIONS Flashcards
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
Create a new dictionary
d = dict()
# or you can do
d = {}
Add a key - value pairs to dictionary
Add a key - value pairs to dictionary
d[‘xyz’] = 123
d[‘abc’] = 345
returns {‘xyz’: 123, ‘abc’: 345}
print the whole dictionary
print the whole dictionary
print(d)
print only the keys
A
# print only the keys
print(d.keys())
returns [‘key1’, ‘key2’,…]
#notice the parens around the keys
print only values
print only values
print(d.values())
returns [value1, value2]
#notice the lack of parens around the values
iterate over dictionary
iterate over dictionary
for i in d :
print(“%s %d” %( i, d[i] ) )
another way of iteration over a dictionary
another method of iteration
for index, value in enumerate(d):
print (index, value , d[value])
check if key exist
check if key exist
print(‘xyz’ in d)
delete the key-value pair
delete the key-value pair
del d[‘xyz’]
Dict.cmp()
Dict.cmp(): Compares elements of both dict.
Dict.len()
Dict.len(): Gives the total length of the dictionary.
Dict.str()
Dict.str(): Produces a printable string representation of a dictionary.
Dict.type()
Dict.type(): Returns the type of the passed variable
Dict.clear()
Dict.clear(): Removes all elements of dictionary dict