简体   繁体   中英

how to create a new key from a value of another key Python

I have a list of dictionaries that looks like the following:

data = [{'Name': 'Paul', 'Date': '20200412', 'ID': '1020'}, {'Name': 'Frank', 'Date': '20200413', 'ID': '1030'}, {'Name': 'Anna', 'Date': '20200414', 'ID': '1040'}]

I need to create a new list of dictionaries, where ID's value would be the key, and the value is another dictionary with key/values associated with this specific ID. This is the desired output:

new_data = [{'1020': {'Name': 'Paul', 'Date': '20200412'}},
{'1030': {'Name': 'Frank', 'Date': '20200413'}},
{'1040': {'Name': 'Anna', 'Date': '20200414'}}]

I have tried:

for index, my_dict in enumerate(data):
    new_data = []
    key = my_dict['ID']
    new_data.append(key)

But that only assigned the key value, not sure how to push it into into a new dict along with other key/values.

>>> [{i['ID']: {k:v for k,v in i.items() if k != 'ID'}} for i in data]
[{'1020': {'Name': 'Paul', 'Date': '20200412'}},
 {'1030': {'Name': 'Frank', 'Date': '20200413'}},
 {'1040': {'Name': 'Anna', 'Date': '20200414'}}]

You could try this list comprehension:

[{x["ID"]: {k: v for k, v in x.items() if k != "ID"}} for x in data]

Which assigns ID as the parent key to the dictionary, and filters out the ID key from the child dictionary inside a dict comprehension

Which could be broken down into this:

result = []
for x in data:
    result.append({x["ID"]: {k: v for k, v in x.items() if k != "ID"}})

And even to a straightforward loop approach:

result = []
for x in data:
    dic = {x["ID"]: {}}
    for k, v in x.items():
        if k != "ID":
            dic[x["ID"]][k] = v
    result.append(dic)

Output:

[{'1020': {'Name': 'Paul', 'Date': '20200412'}}, {'1030': {'Name': 'Frank', 'Date': '20200413'}}, {'1040': {'Name': 'Anna', 'Date': '20200414'}}]
new_data = []
for index, my_dict in enumerate(data):
    key = my_dict['ID']
    del my_dict['ID']
    new_data.append({key:data[index]})

To add the other values you simply need to create a new dict like this:

new_data.append( key:{
'name':my_dict['name']
'Date':my_dict['date']
}

You also don't need to make the 'key' variable, you can just use 'my_dict['ID']'

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