循环键和值,处理键值并将它们存储回Python中的另一个标题

时间:2015-08-29 12:59:31

标签: python list python-2.7 dictionary

我想将字典中存储的所有值相乘。你能否告诉我这样做的好方法。

dict = {'x': [645, 469,456,790,850], 
        'y': [599, 548], 
        'z': [653,  672,150,590],
        'w': [653, 672,150,590]}
list = []
for i, j in dict.iteritems():
    #loop over all key's and get the values out and multiply with 1000
    value_ofkey = float(j[0])
    list.append = value_ofkey *1000
    value_ofkey = float(j[1])
list.append = value_ofkey *1000

3 个答案:

答案 0 :(得分:2)

首先,不要将变量命名为dict,因为它是内置的。

现在要解决您的问题,您可以在字典理解中尝试list-comprehesion

>>> dic = {'x': [645, 469,456,790,850], 
...         'y': [599, 548], 
...         'z': [653,  672,150,590],
...         'w': [653, 672,150,590]}
>>> newdic = {key:[i*1000 for i in val] for key,val in dic.items()}
>>> newdic
{'y': [599000, 548000], 'x': [645000, 469000, 456000, 790000, 850000], 'z': [653000, 672000, 150000, 590000], 'w': [653000, 672000, 150000, 590000]}

发表评论编辑

您可以使用if条件限制所需的密钥。

newdic = {key:[i*1000 if key != 'x' else i for i in val] for key,val in dic.items()}

对于许多此类按键,您可以尝试

newdic = {key:[i*1000 if key not in ('x','y') else i for i in val] for key,val in dic.items()}

工作

>>> newdic = {key:[i*1000 if key != 'x' else i for i in val] for key,val in dic.items()}
>>> newdic
{'y': [599000, 548000], 'x': [645, 469, 456, 790, 850], 'z': [653000, 672000, 150000, 590000], 'w': [653000, 672000, 150000, 590000]}
>>> newdic = {key:[i*1000 if key not in ('x','y') else i for i in val] for key,val in dic.items()}
>>> newdic
{'y': [599, 548], 'x': [645, 469, 456, 790, 850], 'z': [653000, 672000, 150000, 590000], 'w': [653000, 672000, 150000, 590000]}

答案 1 :(得分:0)

我非常确定您要提取所有值,将它们乘以1000,然后将每个新值添加到结果列表中。

此代码将字典值中的所有项目乘以1000并将其添加到results

data = {'x': [645, 469,456,790,850], 
        'y': [599, 548], 
        'z': [653,  672,150,590],
        'w': [653, 672,150,590]}
results = []

for l in data.values():
    results.extend(i*1000 for i in l)

>>> print results
[599000, 548000, 645000, 469000, 456000, 790000, 850000, 653000, 672000, 150000, 590000, 653000, 672000, 150000, 590000]

或者你可以在itertools.chain()的帮助下使用列表理解来在一行代码中实现相同的功能:

import itertools
results = [v*1000 for v in itertools.chain(*data.values())]
>>> print results
[599000, 548000, 645000, 469000, 456000, 790000, 850000, 653000, 672000, 150000, 590000, 653000, 672000, 150000, 590000]

请注意,由于字典的性质没有固有的顺序,列表中值的顺序是不确定的。

如果您想更新字典:

for v in data.values():
    for i in range(len(values)):
        v[i] *= 1000
>>> print data
{'y': [599000, 548000], 'x': [645000, 469000, 456000, 790000, 850000], 'z': [653000, 672000, 150000, 590000], 'w': [653000, 672000, 150000, 590000]}

答案 2 :(得分:0)

您可以对lambda使用字典理解。我将{{item.field1}} {{totalTime(item.date1,item.date2)}} 更改为dict

dict1

输出:

dict1 = {'x': [645, 469,456,790,850], 
        'y': [599, 548], 
        'z': [653,  672,150,590],
        'w': [653, 672,150,590]}


dict2 = {k: map(lambda num: num*1000, v) for k,v in dict1.iteritems()}
print (dict2)