[英]How to extract inner dictionary key/value into a new dictionary in Python?
Given this dictionary:鉴于这本词典:
{
"movies": {
"action": [
{
"title": "Movie A",
"score": 9.7
},
{
"title": "Movie B",
"score": 7.0
}
]
}
}
How would you extract score
and put it in a new dictionary keyed off title
like below?你将如何提取score
,并把它放在键入掀起了新词典title
像下面?
{
"Movie A": 9.7,
"Movie B": 7.0
}
I'm able to do it using traditional loops, but I'm hoping there is a more efficient way in Python.我可以使用传统的循环来做到这一点,但我希望 Python 中有一种更有效的方法。
First of all, I guess you are coming from a Javascript or similar background.首先,我猜你来自 Javascript 或类似的背景。 This data structure is called a dictionary (object is something else) and the inner structures are list
s (not arrays) in Python land.这个数据结构被称为字典(对象是别的东西),内部结构是 Python 中的list
(不是数组)。
Assuming that your dictionary is named d
you can use a dictionary comprehension:假设您的字典名为d
您可以使用字典理解:
print({e["title"]: e["score"] for e in d["movies"]["action"]})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.