修改Python字典中的列表元素

时间:2015-08-10 08:25:31

标签: python dictionary

inventory = {'A':['Toy',3, 1000], 'B':['Toy',8, 1100], 
              'C':['Cloth',15, 1200], 'D':['Cloth',9, 1300], 
               'E':['Toy',11, 1400], 'F':['Cloth', 18, 1500], 'G':['Appliance', 300, 50]}

字母是商品的名称,[]括号中的第一个字段是商品的类别,[]括号中的第二个字段是价格,第三个字段是销售的数字。

我希望价格增加1,结果看起来像。

inventory = {'A':['Toy',4, 1000], 'B':['Toy',9, 1100], 
              'C':['Cloth',16, 1200], 'D':['Cloth',10, 1300], 
               'E':['Toy',12, 1400], 'F':['Cloth', 19, 1500], 'G':['Appliance', 301, 50]} 

然后,循环查找价格为19美元的任何商品的好方法。

我不擅长lambda功能。你能不能给我一些你的代码的解释,以便我可以操作以备将来使用?谢谢

3 个答案:

答案 0 :(得分:2)

试试这个:

for k, v in inventory.iteritems():
    v[1] += 1

然后找到匹配项:

price_match = {k:v for (k,v) in inventory.iteritems() if v[1] == 19}

找到匹配的lambda:

find_price = lambda x: {k:v for (k,v) in inventory.iteritems() if v[1] == x}
price_match = find_price(19)

答案 1 :(得分:0)

您可以使用dict comprehension

>>> new={k:[m,p+1,n] for k,(m,p,n) in inventory.items()}
{'G': ['Appliance', 301, 50], 'E': ['Toy', 12, 1400], 'D': ['Cloth', 10, 1300], 'B': ['Toy', 9, 1100], 'A': ['Toy', 4, 1000], 'C': ['Cloth', 16, 1200], 'F': ['Cloth', 19, 1500]}
>>> 

寻找特殊物品:

>>> {k:[m,p,n] for k,(m,p,n) in new.items() if p==19}
{'F': ['Cloth', 19, 1500]}

答案 2 :(得分:0)

如果您不想“就地”修改数据,您将遍历dict:

for k, v in inventory.iteritems():
    v[1] += 1

如果您使用的是python3,则使用items代替iteritems。使用dict理解{k:[m,p+1,n] for k,(m,p,n) in inventory.items()}的解决方案意味着你将用一个新的obejct替换整个dict(在某些情况下这很好,但在其他情况下没那么好。)