Rad*_*mri 9 python parsing json
我在尝试使用 python 从 json 数组中的特定键获取值列表时遇到问题。使用下面的 JSON 示例,我试图创建一个仅包含name键值的列表。原始 JSON:
[
{
"id": 1,
"name": "Bulbasaur",
"type": [
"grass",
"poison"
]
},
{
"id": 2,
"name": "Ivysaur",
"type": [
"grass",
"poison"
]
}
]
Run Code Online (Sandbox Code Playgroud)
预期的:
["Bulbasaur", "Ivysaur"]
Run Code Online (Sandbox Code Playgroud)
下面是我的方法的代码:
import json
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
print(contents[:]["name"])
Run Code Online (Sandbox Code Playgroud)
我正在尝试采用一种不需要循环每个索引并附加它们的方法,类似于上面的代码。使用python'json库可以使用这种方法吗?
Dev*_*ngh 13
您不能这样做,contents[:]["name"]因为contents列表是具有整数索引的字典,并且您无法使用 string 从中访问元素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)
Run Code Online (Sandbox Code Playgroud)
输出将是
['Bulbasaur', 'Ivysaur']
Run Code Online (Sandbox Code Playgroud)
这不是问题的真正答案。真正的答案是使用列表理解。但是,您可以创建一个类,允许您专门使用您在问题中尝试过的语法。一般的想法是子类化,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)
Run Code Online (Sandbox Code Playgroud)
您的原始代码现在可以开箱即用,只需添加一个额外的包装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"])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16265 次 |
| 最近记录: |