[英]How to count occurrences of a specific dict key in dicts list and some dicts values contains list and append the count in value
I'm trying to count the number of times a specified key occurs in my list
of dict
s.我正在尝试计算指定键在我的dict
list
中出现的次数。 I've used loops and sum to count up all the keys, but how can I find the count for a specific key?我已经使用循环和求和来计算所有键的数量,但如何找到特定键的计数? I have this code, which does not work currently:我有这段代码,目前不起作用:
for dico in data:
for ele in dico['people']:
print(ele['name']+str(len(ele['animals'])))
The "entries" data looks like this: “条目”数据如下所示:
[
{
"name": "Uzuzozne",
"people": [
{
"name": "Lillie Abbott",
"animals": [
{
"name": "John Dory"
}
]
}
]
},
{
"name": "Satanwi",
"people": [
{
"name": "Anthony Bruno",
"animals": [
{
"name": "Oryx"
}
]
}
]
},
{
"name": "Dillauti",
"people": [
{
"name": "Winifred Graham",
"animals": [
{ "name": "Anoa" },
{ "name": "Duck" },
{ "name": "Narwhal" },
{ "name": "Badger" },
{ "name": "Cobra" },
{ "name": "Crow" }
]
},
{
"name": "Blanche Viciani",
"animals":
[{ "name": "Barbet" },
{ "name": "Rhea" },
{ "name": "Snakes" },
{ "name": "Antelope" },
{ "name": "Echidna" },
{ "name": "Crow" },
{ "name": "Guinea Fowl" },
{ "name": "Deer Mouse" }]
}
]
}
]
My goal is to print the counts of People and Animals by counting the number of children and appeng it in the name, eg.我的目标是通过计算孩子的数量并将其附加到名称中来打印人和动物的数量,例如。 Satanwi [2]
. Satanwi [2]
。
[ { name: 'Dillauti [5]',
people:
[ { name: 'Winifred Graham [6]',
animals:
[ { name: 'Anoa' },
{ name: 'Duck' },
{ name: 'Narwhal' },
{ name: 'Badger' },
{ name: 'Cobra' },
{ name: 'Crow' } ] },
{ name: 'Blanche Viciani [8]',
animals:
[ { name: 'Barbet' },
{ name: 'Rhea' },
{ name: 'Snakes' },
{ name: 'Antelope' },
{ name: 'Echidna' },
{ name: 'Crow' },
{ name: 'Guinea Fowl' },
{ name: 'Deer Mouse' } ] },
...
...
]
This will do what you want;这会做你想做的; feel free to ask if you need explanations:随时询问您是否需要解释:
for dico in data:
children = 0
for ele in dico['people']:
animals = len(ele['animals'])
children += 1 + animals
ele['name'] += f" [{animals}]"
dico['name'] += f" [{children}]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.