Ujae Kang
Ujae Kang

Reputation: 167

modifying list element in 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]}

The alphabets are name of merchandise, the first field in the [] brackets are category of the merchandise, the second field in the [] brackets are price, the third are numbers sold.

I would like the price to be increased by 1 so the result would look like.

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

Then what would be a good way to loop through to find any item whose price is $19.

I am not good at lambda function. Could you please give me some explanation of your code so that I could manipulate for future use? Thank you

Upvotes: 1

Views: 94

Answers (3)

Kasravnd
Kasravnd

Reputation: 107287

You can use a 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]}
>>> 

And for finding a special items :

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

Upvotes: 0

skyking
skyking

Reputation: 14360

If you wan't to modify the data "in-place" you would loop through the dict:

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

if you're using python3 you'd use items instead of iteritems. The solution with using dict comprehension {k:[m,p+1,n] for k,(m,p,n) in inventory.items()} means that you will replace the entire dict with a new obejct (which is fine in some scenarios, but not that good in others).

Upvotes: 0

M. Shaw
M. Shaw

Reputation: 1742

Try this:

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

Then to find matches:

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

A lambda to find matches:

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

Upvotes: 2

Related Questions