简体   繁体   English

更新字典中键的值

[英]update the value of key in a dictionary

I want to build a dictionary to count the number of different colors of different fruit.我想建立一个字典来计算不同水果的不同颜色的数量。 Can I build a dictionary term like this?我可以建立一个这样的字典术语吗?

dicts['apple'] = (('red',1),('green',2))

here ('red',1) means the number of red apples is 1, ('green',2) means the number of green apples is 2. If then I find another red apple, so I want to update the ('red',1) to ('red',2) , is it possible?这里('red',1)表示红苹果的数量是 1, ('green',2)表示绿苹果的数量是 2。如果然后我找到另一个红苹果,所以我想更新('red',1) to ('red',2) ,这可能吗? If it is, can you give a code example to implement it?如果是,你能给出一个代码示例来实现它吗?

It is better to use nested dictionary, something like this最好使用嵌套字典,像这样

fruits = {"apple": {"red": 2, "green": 5},
          "grapes": {"red": 6, "green": 0}}

You can make a dictionary that has dictionaries as values (ie a nested dictionary) eg您可以制作一个以字典作为值的字典(即嵌套字典),例如

fruits = { 'apple' : { 'red' : 1, 'green' : 2 },
           'pear' : { 'bartlett' : 2, 'packham' : 4 }
         }

To increment the number of red apples and packham pears:增加红苹果和帕克汉梨的数量:

fruits['apple']['red'] += 1 
fruits['pear']['packham'] += 2
print(fruits)

Output:输出:

{
 'pear': {'packham': 6, 'bartlett': 2},
 'apple': {'green': 2, 'red': 2}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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