-1

For example, I have this dictionary.

{'count': 1, 'items': [{'date': 1649523732, 'from_id': 269690832, 'id': 190, 'out': 0, 'attachments': [{'type': 'photo', 'photo': {'album_id': -3, 'date': 1649523732, **'id': 457249932**, 'owner_id': 269690832, 'access_key': 'df14603asdd3d26e7a1f5'}}]}]}

I want to get the value of id ('id': 457249932). How do i do this?

TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
JustKirill
  • 11
  • 1
  • Let's assume the name of the dictionary variable is `myDict`. Simply use `myDict["items"][0]["attachments"][0]["photo"]["id"]`. Note that, it seems your dictionary is not valid. – TheFaultInOurStars Apr 09 '22 at 17:29
  • I'm wondering is you always know this structure. If these lists are of variable length and you need to find a dict within those lists based on the value of its `id` key, then I'd recommend following [this method](https://stackoverflow.com/a/7079297/2081835). In either case, you should use `dict.get` in place of just referencing these values if there is a chance they won't be there. – theherk Apr 09 '22 at 17:33

1 Answers1

0

The element is nested quite deep -- it's nested inside a list mapped to an items key, a list mapped to an attachments key, and a dictionary mapped to a photo key. So, we can do:

print(data['items'][0]['attachments'][0]['photo']['id'])

where data is the dictionary that you're indexing on.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • That was very useful. Thank you. But i have 1 more queston if i have an array of dicts and i only need a specific one, how do I get it? For example [{'url':'some url', 'type': 's'}, { 'url':'some url', 'type': 'm'}, {'url':'some url', 'type': 'x'}, {'url':'some url', 'type': 'y'}] – JustKirill Apr 09 '22 at 17:45
  • Please take a look at:- https://stackoverflow.com/questions/71799031/how-to-create-a-def-in-python-that-pick-a-specific-value-and-then-make-a-new-d/71799213#71799213 – Ashish Samarth Apr 09 '22 at 18:39