python - Getting an dict by name with in a list with an element key within a variable -


data = {   "items" : [{"potion" : 1}, {"potion2" : 1}] }  print(data["items"][0]["potion"]) 

so, here's jiz. want potion2 without providing number [0] can't because variables has 5 items within list while 1 might have 3 items providing number might not giving me need. there way potion2 without providing number before it?

i'm assuming don't want provide index because hard coding not work in circumstances.

you can pull out items in list have key.

build list of items, have key. might ordinarily one, container not enforce 1 entry can have key.

after can either iterate on list or check if returned value empty , take first element.

>>> data = {'items': [{'potion': 1}, {'potion2': 1}]} >>> e = filter(lambda i: 'potion' in i, data['items']) >>> in e: ...     print(i['potion']) ...  1 

or pull out first element. realize said no indices, index applied filtered list , check not empty first, it's valid thing do.

>>> if e: ...     print(e[0]['potion']) ...  1 

Comments