Python adding the values

# 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

Answers (2)

Stjonal
Stjonal

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:

  1. iterating over the list of dictionaries to get at each different dictionary.
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.

  1. iterating over the keys in the dictionary. The method dict.keys() returns a list of keys, over which can be iterated.
for k in d.keys():
  1. finally, for each key in the dictionary the corresponding key in the result dictionary is modified to add the new value. with 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

LiiVion
LiiVion

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

Related Questions