简体   繁体   English

从一个字典中提取多个键:值对到一个新的字典

[英]Extract multiple key:value pairs from one dict to a new dict

I have a list of dict what some data, and I would like to extract certain key:value pairs into a new list of dicts.我有一个包含一些数据的 dict 列表,我想将某些键:值对提取到一个新的 dict 列表中。 I know one way that I could do this would be to use del i['unwantedKey'] , however, I would rather not delete any data but instead create a new dict with the needed data.我知道我可以这样做的一种方法是使用del i['unwantedKey'] ,但是,我宁愿不删除任何数据,而是创建一个包含所需数据的新字典。

The column order might change, so I need something to extract the two key:value pairs from the larger dict into a new dict.列顺序可能会改变,所以我需要一些东西从较大的字典中提取两个键:值对到一个新的字典中。

Current Data Format当前数据格式

[{'Speciality': 'Math', 'Name': 'Matt', 'Location': 'Miami'},
 {'Speciality': 'Science', 'Name': 'Ben', 'Location': 'Las Vegas'}, 
 {'Speciality': 'Language Arts', 'Name': 'Sarah', 'Location': 'Washington DC'},
 {'Speciality': 'Spanish', 'Name': 'Tom', 'Location': 'Denver'},
 {'Speciality': 'Chemistry', 'Name': 'Jim', 'Location': 'Dallas'}]

Code to delete key:value from dict从字典中删除键:值的代码

import csv

data= []
for line in csv.DictReader(open('data.csv')):
    data.append(line)

for i in data:
    del i['Speciality']

print data

Desired Data Format without using del i['Speciality']不使用del i['Speciality']所需的数据格式

[{'Name': 'Matt', 'Location': 'Miami'}, 
 {'Name': 'Ben', 'Location': 'Las Vegas'}, 
 {'Name': 'Sarah', 'Location': 'Washington DC'}, 
 {'Name': 'Tom', 'Location': 'Denver'}, 
 {'Name': 'Jim', 'Location': 'Dallas'}]

If you want to give a positive list of keys to copy over into the new dictionaries: 如果要提供肯定的键列表以复制到新词典中:

import csv

with open('data.csv', 'rb') as csv_file:
    data = list(csv.DictReader(csv_file))

keys = ['Name', 'Location']
new_data = [dict((k, d[k]) for k in keys) for d in data]

print new_data

suppose we have, 假设我们有,

l1 = [{'Location': 'Miami', 'Name': 'Matt', 'Speciality': 'Math'},
      {'Location': 'Las Vegas', 'Name': 'Ben', 'Speciality': 'Science'},
      {'Location': 'Washington DC', 'Name': 'Sarah', 'Speciality': 'Language Arts'},
      {'Location': 'Denver', 'Name': 'Tom', 'Speciality': 'Spanish'},
      {'Location': 'Dallas', 'Name': 'Jim', 'Speciality': 'Chemistry'}]

to create a new list of dictionaries that do not contain the keys 'Speciality' we can do, 创建不包含键“ Speciality”的新词典列表,

l2 = []
for oldd in l1:
    newd = {}
    for k,v in oldd.items():
        if k != 'Speciality':
            newd[k] = v
    l2.append(newd)

and now l2 will be your desired output. 现在l2将是您想要的输出。 In general you can exclude an arbitrary list of keys like so 通常,您可以像这样排除任意键列表

exclude_keys = ['Speciality', 'Name']
l2 = []
    for oldd in l1:
        newd = {}
        for k,v in oldd.items():
            if k not in exclude_keys:
                newd[k] = v
        l2.append(newd)

the same can be done with an include_keys variable 使用include_keys变量也可以做到这一点

include_keys = ['Name', 'Location']
l2 = []
    for oldd in l1:
        newd = {}
        for k,v in oldd.items():
            if k in include_keys:
                newd[k] = v
        l2.append(newd)

You can create a new list of dicts limited to the keys you want with one line of code (Python 2.6+): 您可以使用一行代码(Python 2.6+)创建新的字典列表,将其限制为所需的键:

NLoD=[{k:d[k] for k in ('Name', 'Location')} for d in LoD]

Try it: 试试吧:

>>> LoD=[{'Speciality': 'Math', 'Name': 'Matt', 'Location': 'Miami'},
 {'Speciality': 'Science', 'Name': 'Ben', 'Location': 'Las Vegas'}, 
 {'Speciality': 'Language Arts', 'Name': 'Sarah', 'Location': 'Washington DC'},
 {'Speciality': 'Spanish', 'Name': 'Tom', 'Location': 'Denver'},
 {'Speciality': 'Chemistry', 'Name': 'Jim', 'Location': 'Dallas'}]
>>> [{k:d[k] for k in ('Name', 'Location')} for d in LoD]
[{'Name': 'Matt', 'Location': 'Miami'}, {'Name': 'Ben', 'Location': 'Las Vegas'}, {'Name': 'Sarah', 'Location': 'Washington DC'}, {'Name': 'Tom', 'Location': 'Denver'}, {'Name': 'Jim', 'Location': 'Dallas'}]

Since you are using csv, you can limit the columns that you read in the first place to the desired columns so you do not need to delete the undesired data: 由于您使用的是csv,因此可以将首先读取的列限制为所需的列,这样就无需删除不需要的数据:

dc=('Name', 'Location')        
with open(fn) as f:
    reader=csv.DictReader(f)
    LoD=[{k:row[k] for k in dc} for row in reader]
keys_lst = [Name', 'Location]

new_data={key:val for key,val in event.items() if key in keys_lst}
print(new_data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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