简体   繁体   中英

summing elements of multiple dictionary lists with zip

I have dictionary keys as defined below:

d['abc']=[1,2,3]
d['def']=[2,4,6]

zipped_list_1=zip()
zipped_list_1.append(d['abc'])
zipped_list_1.append(d['def'])

print zipped_list_1
[[1, 2, 3], [2, 4, 6]]<----I want to get [d['abc'],d['abc']] instead
print [sum(item) for item in zipped_list_1]
[6,12]<------------I want [(3),(6),(9)] instead

Here is an example: Python: Sum of element for n-lists but it doesnt talk about dicts.

The way you're building your zipped_list_1 will not produce the results you expect. If you're sure the lists that are elements of your dictionary are of equal length, you want something like:

zipped_list_1 = zip(*d.values())
print [sum(item) for item in zipped_list_1]

d.values() returns a list of the elements of your dict - in this case, the sublists, so it evaluates to [[1,2,3], [2,4,6]] . The * operator then assigns its values as positional parameters to zip - for the input you listed it's equivalent to calling zipped_list_1 = zip([1, 2, 3], [2, 4, 6]) . That will give you [[1, 2], [2, 4], [3, 6]] in zipped_list_1 , so the sum list comprehension will behave as you expect.

You would probably want something like this:

d = {}
d['a']=[1,2,3]
d['b']=[2,4,6]

zipped_list = zip(d['a'],d['b'])
print map(lambda x: sum(x), zipped_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM