[英]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()
employees
is a list of dictionaries so you can just directly index the list to get Michell: employees
是一个字典列表,所以你可以直接索引这个列表来得到 Michell:
newDict = employees[1]
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.