当前位置: 动力学知识库 > 问答 > 编程问答 >

python: directory with values other then occurrence of keys

问题描述:

How can I make a directory have values count from a list that is associated with the Keys, opposed to the occurrences of a particular Key.

EXAMPLE: I have two lists, One is of strings, and one is of a values for each string.

say:

strings = ['me', 'you', 'me', 'her','her']

values = [1,20,6,35,5]

and I want:

directory = {'me':7, 'you':20, 'her':40}

This is how I have been making directories:

d = {}

for i in list:

if i in d:

d[i] = d[i]+1

else:

d[i] = 1

valueKeys = zip(d.values(),d.keys())

value = d.values()

keys = d.keys()

网友答案:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for x, y in zip(strings, values):
...     d[x] += y
...
>>> d
defaultdict(<class 'int'>, {'you': 20, 'her': 40, 'me': 7})

The resulted defaultdict object can act as plain dict:

for key in d:
    print(key, d[key])

Output:

me 7
her 40
you 20
网友答案:
    #x=numbers
    #list = names
    d = {}
    for i in list:
        if i in d:
            d[i] = d[i]+x[list.index(i)]
        else:
            d[i] = x[list.index(i)]
    valueKeys = zip(d.values(),d.keys())
    value = d.values()
    keys = d.keys()

This was how I solved it

分享给朋友:
您可能感兴趣的文章:
随机阅读: