简体   繁体   English

如何将一个字典中的给定键从另一个字典中提取到一个新字典中(Python)

[英]How to extract the given keys in one dictionary from another into a new dictionary (Python)

I'm trying to practice sets and dictionaries, and one thing I've been finding is myself stuck on this practice problem over and over.我正在尝试练习集合和字典,我发现的一件事是我自己一遍又一遍地坚持这个练习问题。

For example if I have a dictionary like例如,如果我有一本像

employees =[
{
    "name": "Jamie Mitchell",
    "job": "Head Chef",
    "city": "Toronto",
    "age": 80,
    "status": "Working"
},
{
    "name": "Michell Anderson",
    "job": "Line Cook",
    "city": "Mississauga",
    "age": 56,
    "status": "Lunch Break"
  }
]

How would I extract the second part of the dictionary from the first in order to only have the information on the right be in a new dictionary?我将如何从第一部分中提取字典的第二部分,以便只有右侧的信息出现在新字典中?

I'm trying something like:我正在尝试类似的东西:

extractedInfo = []

for employee in employees:
    for key in keys:
        extractedInfo.append(employee[key])

newDict = {extractedInfo[i]: extractedInfo[i + 1] for i in range(0, len(extractedInfo), 2)}
print(newDict)

New Dictionary would look like : (Jamie, Chef, Toronto , 80 , Working , Michell , Line Cook, Mississauga, 56 , Lunch Break)新词典看起来像 :(Jamie, Chef, Toronto, 80 , Working , Michell , Line Cook, Mississauga, 56 , Lunch Break)

However I know I'm doing something wrong, as I'm not sure what to initialize "Keys" as.但是我知道我做错了什么,因为我不确定将“密钥”初始化为什么。 I'm new to dictionaries and sets and I'm having a hard time.我是字典和集合的新手,我很难过。 Any suggestions or tips on a way to do this would help a lot.任何关于如何做到这一点的建议或提示都会有很大帮助。

EXTRA: What if I wanted to only keep Name and Job values of both employees? EXTRA:如果我只想保留两个员工的 Name 和 Job 值怎么办?

You have them backwards;你把它们倒退了; the outer one [] is a list.外面的[]是一个列表。 The inner ones {} are dictionaries.内部的{}是字典。

You can get the second one with employees[1] (indexing starts from 0) or the last one with employees[-1] (in this case they are the same).您可以使用employees[1]获得第二个(索引从 0 开始)或使用employees[-1]获得最后一个(在这种情况下它们是相同的)。

If you need a copy, you can call .copy() on the result:如果你需要一个副本,你可以在结果上调用.copy()

second_employee = employees[1]
copied_details = second_employee.copy()

Quick Answer:快速回答:

employees is a list of dictionaries so you can just directly index the list to get Michell: employees是一个字典列表,所以你可以直接索引这个列表来得到 Michell:

newDict = employees[1]

More Detailed Answer:更详细的答案:

Firstly, here is how you create a key-value pair in a dictionary:首先,这是在字典中创建键值对的方法:

dct = {}
dct['color'] = 'blue' # dct = {'color':'blue'}

Knowing this, all you would need to copy a dictionary is the keys and values.知道了这一点,复制字典所需的只是键和值。 You can use the .keys() , .values() , and .items() methods of dictionaries to do this.您可以使用.keys().values().items()方法来执行此操作。

dct.keys() # returns a list of all the keys -> ['color']
dct.values() # returns a list of all the values -> ['blue']
dct.items() # return a list of all the pairs as tuples -> [('color','blue')]

There are other options to copy as another user has mentioned however I strongly suggest you get used to work with the 3 methods listed above.正如另一位用户所提到的,还有其他选项可供复制,但我强烈建议您习惯使用上面列出的 3 种方法。 If you haven't already, make sure you are really comfortable with lists before you jump into dictionaries and combined structures.如果您还没有,请确保您在进入字典和组合结构之前对列表非常熟悉。 You already seem to know how to work loops so hopefully this is helpful enough, good luck!您似乎已经知道如何使用循环,所以希望这对您有帮助,祝您好运!

What you are trying to do will return NameError name 'keys' is not defined.您尝试执行的操作将返回NameError name 'keys' is not defined. . .

for employee in employees:
     for key in keys:
         extractedInfo.append (employee [key])

To obtain the result of employees that you are describing, you have to create a loop with an array that adds the new values in each iteration , by this way:要获得您所描述的employees的结果,您必须通过以下方式创建一个带有array循环,该array在每次迭代中添加新

>>> info = []
>>> for employe in employees:
...     new_employe = []
...     for key in employe.keys():
...         new_employe.append(employe[key])
...     info.append(new_employe)
...
>>> info

... ...

[['Jamie Mitchell', 'Head Chef', 'Toronto', 80, 'Working'], ['Michell Anderson', 'Line Cook', 'Mississauga', 56, 'Lunch Break']]

暂无
暂无

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

相关问题 从一个字典的键和另一个字典的值构建一个新字典 - Build a new dictionary from the keys of one dictionary and the values of another dictionary 如果一个字典中的键与另一个字典中的键匹配,如何返回新字典? - How do I return a new dictionary if the keys in one dictionary, match the keys in another dictionary? 从一个字典的键和另一个字典 python 的对应值创建字典 - Create a dictionary from the keys of one dictionary and corresponding values of another dictionary python 如何从与另一个列表中的键匹配的字典列表中提取值 - How to extract values from list of dictionary that match the keys in another list 如何通过修改特定值从另一个字典创建新字典(将两个键的值合二为一) - How to create a new dictionary from another one by modifying specific values (join the values of two keys into one) 从Python中的字典中拉出彼此不相等的随机键 - Pull random keys from dictionary in Python that are not equal to one another Python:将公用密钥从一个字典应用于另一个字典 - Python: Applying common keys from one Dictionary to another Python 使用相同的键将一个字典中的值附加到另一个字典 - Python appending values from one dictionary to another with the same keys 如何从python中的字典中检索具有给定值的所有键 - how to retrieve all keys with a given value from dictionary in python 如何从 Python 中的字典中提取特定键的列表? - How to extract list of specific keys from the dictionary in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM