Python adding the values - python

# 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

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))

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:
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.
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():
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.

Related

Comparing the strings in key and value of the same dictionary

I am looking to solve a problem to compare the string of the key and value of the same dictionary.
To return a dictionary of all key and values where the value contains the key name as a substring.
a = {"ant":"antler", "bi":"bicycle", "cat":"animal"}
the code needs to return the result:
b = {"ant":"antler", "bi":"bi cycle"}
You can iterate through the dictionary and unpack the key and the value at the same time this way:
b = {}
for key, value in a.items():
if value in key:
b[value] = key
This will generate your wanted solution. It does that by unpacking both the key and the value and checking if they match afterward.
You can also shorten that code by using a dictionary comprehension:
b = {key:value for key, value in a.items() if key in value}
This short line does the exact same thing as the code before. It even uses the same functionalities with only one addition - a dictionary comprehension. That allows you to put all that code in one simple line and declare the dictionary on the go.
answer = {k:v for k,v in a.items() if k in v}
Notes:
to iterate over key: value pair we use dict.items();
to check if a string is inside some other string we use in operator;
to filter items we use if-clause in the dictionary comprehension.
See also:
about dictionary comprehensions
about operators in and not in

How to add all the values to a dictionary using for loop?

I have the keys as key1= [(0,0,0), (0,0,1),(1,0,0), (0,1,0)]
for x1,x2,x3 in key1:
summat= #some expression that has new value for each keys
tempDict ={(x1,x2,x3): summat}
print(tempDict)
It only prints the last value(0,1,0) and the summat of last value but I want to store all the values of summat for all the value of keys
Try replacing what you have into a dictionary comprehension:
tempDict = {key: summat(key) for key in key1}
This is the equivalent to:
tempDict = {}
for key in key1:
tempDict.update({key: summat(key)}
Your code will overwrite the value of tempDict each iteration, so at the end you'll only see the last value.

Strip nested dict of non zero values

I'm trying to strip a nested dict (only 1 level deep eg: some_dict = {'a':{}, b:{}} all all non-zero and none values.
However I'm not sure who to reassemble the dict properly, the below gives me a key error.
def strip_nested_dict(self, some_dict):
new_dict = {}
for sub_dict_key, sub_dict in some_dict.items():
for key, value in sub_dict.items():
if value:
new_dict[sub_dict_key][key] = value
return new_dict
You need to create the nested dictionary before accessing it:
for sub_dict_key, sub_dict in some_dict.items():
new_dict[sub_dict_key] = {} # Add this line
for key, value in sub_dict.items():
# no changes
(In order for new_dict[sub_dict_key][key] to work, new_dict must be a dictionary, & new_dict[sub_dict_key] also has to be a dictionary.)
This worked. Shame you can't just assign a nested value without having to create an empty for for each key first.
def strip_nested_dict(self, some_dict):
new_dict = {}
for sub_dict_key, sub_dict in some_dict.items():
new_dict[sub_dict_key] = {}
for key, value in sub_dict.items():
if value:
new_dict[sub_dict_key][key] = value
return new_dict

accesing data in a dictionary python

so i have this code:
dic1 = { "data1":1, "data2":2, "data3":3}
dic2 = { "data1":4, "data2":5, "data3":6}
dic3 = { "data1":7, "data2":8, "data3":9}
data = [dic1, dic3, dic2]
how can i access the data in the dictionaries from a function if the input is the list?
so if i have a for:
for x in data:
if x == "dic1":
print dic1["data1"]
print dic1["data2"]
elif x == "dic2":
print dic2["data1"]
and so on......
that will work but only because i know that those dictionaries exist but if another dictionary is created that method will obviously not work, so how can i do it.
Use
for x in data:
for k, v in x.items():
print k, v
So the key here is to use the items method to access to the dictionary's elements.
The first loop iterates over dictionaries, the second loop iterates over keys of dictionary considered by the first loop. Then you print every element:
for dictionary in data:
for key in dictionary:
print dictionary[key]

deleting entries in a dictionary based on a condition

I have a dictionary with names as key and (age, Date of Birth) tuple as the value for those keys. E.g.
dict = {'Adam' : (10, '2002-08-13'),
'Eve' : (40, '1972-08-13')}
I want to delete all the keys which have age > 30 for their age in value tuple, how can I do that? I am accessing age of each key using dict[name][0] where dict is my dictionary.
The usual way is to create a new dictionary containing only the items you want to keep:
new_data = {k: v for k, v in data.items() if v[0] <= 30}
If you need to change the original dictionary in place, you can use a for-loop:
for k, v in list(data.items()):
if v[0] > 30:
del data[k]
Note that list(data.items()) creates a shallow copy of the items of the dictionary, i.e. a new list containing references to all keys and values, so it's safe to modify the original dict inside the loop.

Categories

Resources