zzzz
zzzz

Reputation: 55

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? If it is, can you give a code example to implement it?

Upvotes: 0

Views: 69

Answers (2)

Nick
Nick

Reputation: 147146

You can make a dictionary that has dictionaries as values (i.e. a nested dictionary) e.g.

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}
}

Upvotes: 1

mohammed wazeem
mohammed wazeem

Reputation: 1328

It is better to use nested dictionary, something like this

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

Upvotes: 2

Related Questions