我需要查找关键字' p'在字典中。密钥嵌套在列表中的字典中,如下所示:
{
"confidence": 0.2802316236036372,
"words": [
{
"p": 0,
"c": 1,
"s": 1420,
"e": 4250,
"m": "turn",
"w": "Jennifer"
},
{
"p": 1,
"c": 0.487,
"s": 1420,
"e": 1620,
"w": "Hi"
}]}
我试过了:
import json
import pprint
data = json.load(open ('test.json'))
data_list = data["words"]
for word in data_list:
x = str(word['p'])
# word_list = []
# word_list.append(x)
但它只返回各个字符串中的每一个。我尝试将这些附加到列表中但没有成功。我也在考虑制作一个for循环,只计算有多少,但这似乎是一个笨重的方法。我怎么能: 1.创建一个所有字符串的列表,所以我可以删除最后一个?要么 2.创建一个所有字符串的字符串,所以我可以类似地删除最后一个字符串?要么 3.遍历每个"字"在data_list中计算它们?要么 4.获取所有字符串的列表,然后获取该列表的长度? 感谢。
答案 0 :(得分:3)
你过分思考它。要检查密钥是否在dict
中,您只需执行some_key in some_dict
。因此,您只需使用sum
:
In [6]: d = {
...: "confidence": 0.2802316236036372,
...: "words": [
...: {
...: "p": 0,
...: "c": 1,
...: "s": 1420,
...: "e": 4250,
...: "m": "turn",
...: "w": "Jennifer"
...: },
...: {
...: "p": 1,
...: "c": 0.487,
...: "s": 1420,
...: "e": 1620,
...: "w": "Hi"
...: }]}
In [7]: data_list = d['words']
In [8]: sum('p' in sub for sub in data_list)
Out[8]: 2
答案 1 :(得分:0)
您可以在列表解析中使用嵌套的sum
函数:
data_list = {'confidence': 0.2802316236036372, 'words': [{'c': 1, 'e': 4250, 'm': 'turn', 'p': 0, 's': 1420, 'w': 'Jennifer'}, {'p': 1, 'c': 0.487, 'e': 1620, 's': 1420, 'w': 'Hi'}]}
the_count = sum(sum('p' in c for c in b) for a, b in data_list.items() if isinstance(b, list))
输出:
2