Reputation: 1
# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
# printing initial dictionary
print ("initial dictionary", (ini_dict))
# sum the values with same keys
result = {}
for d in ini_dict:
for k in d.keys():
result[k] = result.get(k,0) + d[k]
print("resultant dictionary : ", (result))
Can someone explain the program line by line
Upvotes: 0
Views: 44
Reputation: 1
the first line initialises a list of three dictionaries.
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
next up, the dictionary is printed
print ("initial dictionary", (ini_dict))
finally, a weighted histogram is made of the dictionaries based on the keys of the elements within said dictionaries. This is done in three steps:
for d in ini_dict:
remember: ini_dict
is a list of dictionaries. when you for-loop over a list, the symbol (here d
) becomes each of the dictionaries.
dict.keys()
returns a list of keys, over which can be iterated.for k in d.keys():
result.get(k,0)
the value for the key k in the result dictionary is fetched, but 0
is the default value if the key is not present.result[k] = result.get(k,0) + d[k]
This just replaces the result with the previous result + the value in d.
At the end of this bit of code, the result dictionary has the added value of each of the keys.
Upvotes: 0
Reputation: 318
Creating a list of dictionary's
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
Prints out the list with dictionary's
print ("initial dictionary", (ini_dict))
Creates a new dictionary
result = {}
Loop's through the List of dictionarys
for d in ini_dict:
so the first d
would be {'a':5, 'b':10, 'c':90}
Loop's through the keys of that dict
for k in d.keys():
-> a, b and c
Creates or gets the same key in the result dict and adds the value from the current key. Default value for a new created key is 0.
result[k] = result.get(k,0) + d[k]
Prints out the result
dict
print("resultant dictionary : ", (result))
Upvotes: 2