简体   繁体   中英

Associate multiple key/values to a defaultdict(list)

I have json_data object with a list of records. I need all 'id' in a list and I want to somehow associate the value from the 'room' and 'name' key to the id list. The reason why I need all IDs in a list is because Im working with an API that takes in IDs as a list for bulk processing. I also need to associate the value from the 'name' and 'room' key to the id list. I am able to associate 'room' to the list using a defaultdict(list) but not sure how to also also associate the value of the 'name' key. How should I do this?

json_data = {
    "records": [
    {
        "id": 123,
        "name": "John",
        "room": "32B"
    },
    {
        "id": 456,
        "name": "Mary",
        "room": "32B"
    },
        {
        "id": 789,
        "name": "Gary",
        "room": "16F"
    }]
}

data_list = json_data['records']
my_default_dict = defaultdict(list)
for data in data_list:
    my_default_dict[data['room']].append(data['id'])
    # This gives {'32B': [123, 456], '16F': [789]}

Why not convert your data into a map of IDs? You can then extract the ID list as keys from the map.

records = json_data['records']
# Warning! This destructively iterates over json_data.
json_map = dict(zip((d.pop('id') for d in records), records))

json_map
# {123: {'name': 'John', 'room': '32B'},
#  456: {'name': 'Mary', 'room': '32B'},
#  789: {'name': 'Gary', 'room': '16F'}}

id_list = list(json_map)
# [123, 456, 789]

You can group your records by 'room' .

records = json_data['records']
new_records = defaultdict(list)
for record in records:
    new_records[record['room']].append(record)

Then you can get a list of 'id' s.

ids_for_32b = [item['id'] for item in new_records['32B']]
print(ids_for_32b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM