Posts

Showing posts with the label Python(Dictionary)

How to iterate dictionaries using for loops in Python

Image
With for loops, we can iterate a dictionary by key, value or both of them: By key: >>> d = {'a':12, 'b':2, 'c':21} >>> for key in d: print(key, end=' ') a b c  >> >  By value: >>> for value in d.values(): print(value, end=' ') 12 2 21  >>>  By both key and value: >>> for key, value in d.items(): print(key+ ":"+ str(value)) a:12 b:2 c:21 >>>  Caveat, please check the following code: >>> for key in d: print(key + ':' + str(d[key])) a:12 b:2 c:21 >>>  It does the same thing as the d.items() code, but d[key] inside a for loop caused the keys to be hashed again, which is not efficient if the dictionary is large.

How to merge two dictionaries in Python?

Image
 If you want merge two dictionaries without affecting the original ones, you could do the following: x = {'a':2, 'b':1} y = {'b':3, 'c':33} z = x.copy() # makes a shallow copy of x z.update(y)  # overides the values with the same key with y's value {'a': 2, 'b': 3, 'c': 33} or you can put those code in a function: def merge_dict(d1, d2):     z = d1.copy()     z.update(d2)     return z z = merge_dict(x,y) {'a': 2, 'b': 3, 'c': 33} Since Python 3.5, you could just use the following single line to achieve this: z = {**x, **y} {'a': 2, 'b': 3, 'c': 33} And also you coud pass literals notations in: z = {**x, 'd':11,'e':33,**y} {'a': 2, 'b': 3, 'd': 11, 'e': 33, 'c': 33}