Update: I realize now that errors can occur when you scale down your code and then post a question. This is the same question but with the sample code matching the true situation. I also learned that you don't need the line continuation "\" when your python expression is ending in a comma ",".
I can certainly get my projection/sum dictionary by using for
loops, but is there a more Pythonic method? If for
loops must be used is there a 'best python practice'.
Also, if any of my wording is off please let me know the proper way to frame this using python terminology.
Here is the code:
import sys
from collections import defaultdict
D = defaultdict(int)
while True:
D = { ('a', 'mike'): 1,
('b', 'mike'): 2,
('c', 'mike'): 3,
('b', 'tom'): 1,
('e', 'mary'): 11,
('k', 'mike'): 2,
('f', 'mike'): 1,
('z', 'tom'): 1,
}
#print (D)
# how to create prD:
prD_A = defaultdict(int)
prD_A = { 'mike': 9, 'tom': 2, 'mary': 11 }
#Answer supplied by Delirious Lettuce:
prD_B = defaultdict(int)
for k, v in D.items():
_, name = k
prD_B[name] += v
#print(prD_B)
if prD_A == prD_B:
print("Same result")
sys.exit() # END PROGRAM
You were asked in the comments whether or not your keys were supposed to be strings (of tuples) or tuples themselves. Since you didn't really answer, here are two versions which account for both possibilities.
# Keys as strings of tuples
In[2]: correct = {'mike': 9, 'tom': 2, 'mary': 11}
In[3]: my_dict = {
...: "('a', 'mike')": 1,
...: "('b', 'mike')": 2,
...: "('c', 'mike')": 3,
...: "('b', 'tom')": 1,
...: "('e', 'mary')": 11,
...: "('k', 'mike')": 2,
...: "('f', 'mike')": 1,
...: "('z', 'tom')": 1
...: }
In[4]: from ast import literal_eval
...: from collections import defaultdict
...:
...: result = defaultdict(int)
...: for k, v in my_dict.items():
...: _, name = literal_eval(k)
...: result[name] += v
...:
In[5]: result == correct
Out[5]: True
# Keys as actual tuples
In[6]: my_dict_2 = {
...: ('a', 'mike'): 1,
...: ('b', 'mike'): 2,
...: ('c', 'mike'): 3,
...: ('b', 'tom'): 1,
...: ('e', 'mary'): 11,
...: ('k', 'mike'): 2,
...: ('f', 'mike'): 1,
...: ('z', 'tom'): 1
...: }
In[7]: from collections import defaultdict
...:
...: result_2 = defaultdict(int)
...: for k, v in my_dict_2.items():
...: _, name = k
...: result_2[name] += v
...:
In[8]: result_2 == correct
Out[8]: True
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments