我在尝试使用python从json数组中的特定键中获取值列表时遇到麻烦。使用下面的JSON示例,我试图创建一个仅包含name
键值的列表。
原始JSON:
[
{
"id": 1,
"name": "Bulbasaur",
"type": [
"grass",
"poison"
]
},
{
"id": 2,
"name": "Ivysaur",
"type": [
"grass",
"poison"
]
}
]
预期:
["Bulbasaur", "Ivysaur"]
下面是我的方法的代码:
import json
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
print(contents[:]["name"])
我正在尝试一种不需要循环每个索引并附加它们的方法,就像上面的代码一样。使用python的json库可以实现这种方法吗?
答案 0 :(得分:1)
您无法执行contents[:]["name"]
,因为contents
是一个包含整数索引的字典列表,并且您不能使用字符串name
来访问元素。
要解决此问题,您需要遍历列表并为每个name
获取密钥item
的值
import json
contents = []
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
li = [item.get('name') for item in contents]
print(li)
输出将为
['Bulbasaur', 'Ivysaur']
答案 1 :(得分:1)
尝试使用list comprehensions:
print([d["name"] for d in contents])
答案 2 :(得分:1)
这不是该问题的真实答案。真正的答案是使用列表理解。但是,您可以创建一个类,该类允许您专门使用在问题中尝试过的语法。总体思路是将list
子类化,以便像[:]
这样的切片将特殊视图(另一个类)返回到列表中。然后,该特殊视图将允许同时从所有词典中进行检索和分配。
class DictView:
"""
A special class for getting and setting multiple dictionaries
simultaneously. This class is not meant to be instantiated
in its own, but rather in response to a slice operation on UniformDictList.
"""
def __init__(parent, slice):
self.parent = parent
self.range = range(*slice.indices(len(parent)))
def keys(self):
"""
Retreives a set of all the keys that are shared across all
indexed dictionaries. This method makes `DictView` appear as
a genuine mapping type to `dict`.
"""
key_set = set()
for k in self.range:
key_set &= self.parent.keys()
return key_set
def __getitem__(self, key):
"""
Retreives a list of values corresponding to all the indexed
values for `key` in the parent. Any missing key will raise
a `KeyError`.
"""
return [self.parent[k][key] for k in self.range]
def get(self, key, default=None):
"""
Retreives a list of values corresponding to all the indexed
values for `key` in the parent. Any missing key will return
`default`.
"""
return [self.parent[k].get(key, default) for k in self.range]
def __setitem__(self, key, value):
"""
Set all the values in the indexed dictionaries for `key` to `value`.
"""
for k in self.range:
self.parent[k][key] = value
def update(self, *args, **kwargs):
"""
Update all the indexed dictionaries in the parent with the specified
values. Arguments are the same as to `dict.update`.
"""
for k in self.range:
self.parent[k].update(*args, **kwargs)
class UniformDictList(list):
def __getitem__(self, key):
if isinstance(key, slice):
return DictView(self, key)
return super().__getitem__(key)
您的原始代码现在可以直接使用,UniformDictList
中只需换行即可。
import json
try:
with open("./simple.json", 'r') as f:
contents = UniformDictList(json.load(f))
except Exception as e:
print(e)
print(contents[:]["name"])