Python - 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
# 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
dic = {“A”:1, “B”:2}
How would we access the above values?
dic = {“A”:1, “B”:2}
print(dic.get(“A”))
print(dic.get(“C”))
print(dic.get(“C”,”Not Found ! “))
Given three arrays sorted in non-decreasing order, print all common elements in these arrays.
ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
First convert all three lists into dictionaries having elements as keys and their frequencies as value, using Counter() method.
Now perform intersection operation for three dictionaries, this will result us dictionary having common elements among three array list with their frequencies.
# Function to find common elements in three # sorted arrays from collections import Counter
def commonElement(ar1,ar2,ar3): # first convert lists into dictionary ar1 = Counter(ar1) ar2 = Counter(ar2) ar3 = Counter(ar3)
# perform intersection operation resultDict = dict(ar1.items() & ar2.items() & ar3.items()) common = []
# iterate through resultant dictionary # and collect common elements for (key,val) in resultDict.items(): for i in range(0,val): common.append(key) print(common)
# Driver program if \_\_name\_\_ == "\_\_main\_\_": ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] commonElement(ar1,ar2,ar3)
#Output [80, 20]
How to merge two dictionaries using update() ?
Using the method update()
By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None. Example: # Python code to merge dict using update() method def Merge(dict1, dict2): return(dict2.update(dict1))
# Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4}
# This return None print(Merge(dict1, dict2))
# changes made in dict2 print(dict2)
How to merge two dictionaries using ** ?
Using ** in Python
# Python code to merge dict using a single # expression
dict1 = {'a':1, 'b':2} dict2 = {'c':3, 'd':4}
dict3 = {**dict1, **dict2}
_________________
This is generally considered a trick in Python where a single expression is used to merge two dictionaries and stored in a third dictionary. The single expression is **. This does not affect the other two dictionaries. ** implies that the argument is a dictionary. Using ** [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer **kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.