I have a dictionary with keys and a list attached as value to each key. I have to traverse list value attached to each key and segregate them into two different lists with '0' and '1' ( as '0' and '1' are the values in the list) also with the count of '0' , '1' and the total. Please let me know how should i go abut doing this. Thanks
#to loop through a dictionary
total_0 = 0
list_0 =[]
total_1 = 0
list_1 = []
somedict = {'key1':[1,1,1,0,1,0]}
for key,value in somedict.items():
# now loop through each list of your dict, since value keep your list
for item in value:
if item == 1:
total_1 += 1
list_1.append(item)
else :
total_0 += 1
list_0.append(item)
Thats an example, if you explain it with detail, i will try to help you more (:
The problem is abundantly under-specified (are the two different lists supposed to be mutually exclusive? What happens if a key has a list with both 0
and 1
, or neither? Etc). But if for example there is no mutual exclusion constraint, the counts must count each 0 or 1 repeatedly if it occurs repeatedly, and many other guesses about conditions you just don't mention at all...:
def weird_op(d):
keysw0 = []
keysw1 = []
count0s = count1s = 0
for k, v in d.iteritems():
n0 = v.count('0')
n1 = v.count('1')
if n0: keysw0.append(k)
if n1: keysw1.append(k)
count0s += n0
count1s += n1
return keysw0, keysw1, count0s, count1s
I've omitted the "also the total" part of your request because, for that one, the lack of specs borders on the nightmare -- total of WHAT?! Keys, items in the lists, angels dancing on the point of a pin...?! And since you very specifically mention that the lists' items are strings (you do use quotes around them, which must mean strings -- right...?) how the flip do you propose to "total" them?!
If you can clarify the specs (especially that weird "total" one!) no doubt better approaches can be found, but this is the boundary to which my mind-reading patented crystal ball can push. BTW, as part of the specs, some examples of input dict-of-lists and expected results for each would really really help.