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
# 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
Dict.copy()
Dict.copy(): Returns a shallow copy of dictionary dict
Dict.fromkeys()
Dict.fromkeys(): Create a new dictionary with keys from seq and values set to value.
Dict.get()
Dict.get(): For key, returns value or default if key not in dictionary
Dict.get(key, default=None)
Dict.has_key()
Dict.has_key(): Returns true if key in dictionary dict, false otherwise
Dict.items()
Dict.items(): Returns a list of dict’s (key, value) tuple pairs
Dict.keys()
Dict.keys(): Returns list of dictionary dict’s keys
Dict.setdefault()
Dict.setdefault(): Set dict[key]=default if key is not already in dict
Dict.update()
Dict.update(): Adds dictionary dict2’s key-values pairs to dict
Dict.values()
Dict.values(): Returns list of dictionary dict’s values