-1

Hello there I have a JSON dataset with a whole bunch of entries like that: There are multiple entries for each date that look the same, just different dates with multiple entries of people added to that date. So I could get information by using {json_content['12-1-2021'][0]['name']}

    {'12-1-2021': [{'initials': 'IS',
    'name': 'Sam',
    'age': 23,
    'address': 'Freedom Dr',
    'city': 'Seattle',
    'state': 'WA'},
{'initials': 'SD',
'name': 'Sed',
'age': 21,
'address': 'Washington Dr',
'city': 'Phoenix',
'state': 'AZ'}]}

I want to iterate somehow through the dataset and select for instance all the people who live in Seattle without the date(maybe add the date later- not sure the requirement on that yet). But I can't do that without specifying the date since the beginning.

Thank you!

joshmeranda
  • 3,001
  • 2
  • 10
  • 24
Sergey V.
  • 81
  • 9
  • Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – mkrieger1 Nov 22 '21 at 17:48

2 Answers2

0

You definitely can. Since you don't care about the keys of the dictionary just go through the values:

names = [
  person['name']
  for date in json_content.values()
  for person in date if person['city'] == 'Seattle'
]

If you don't want to make any assumptions about how valid the structure of the json is, you can check it explicitly along the way in addition to checking the city:

[
  person['name']
  for date in json_content.values() if isinstance(date, list)
  for person in date if all([
    isinstance(person, dict),
    'name' in person,
    'city' in person,
    person['city'] == 'Seattle'])
]

Both of these get you ['Sam'] for your sample json.

rudolfovic
  • 3,163
  • 2
  • 14
  • 38
0

If you want a complete person record and you are having future scope for a date then I will suggest the below code.

for person_records in json_content.values():
    if isinstance(person_records, list):
        for person in person_records:
            if person.get("city") == "Seattle":
                print(person)
rudolfovic
  • 3,163
  • 2
  • 14
  • 38
raviraj
  • 335
  • 4
  • 19