Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python计算字典列表中的值_Python_List_Dictionary - Fatal编程技术网

Python计算字典列表中的值

Python计算字典列表中的值,python,list,dictionary,Python,List,Dictionary,假设我有以下词典列表: c=[ {“姓名”:“汤姆”,“年龄”:10,“标签”:“孩子”}, {“姓名”:“马克”,“年龄”:35,“标签”:“成人”}, {“name”:“Pam”,“age”:70,“tag”:“very old”}, {“姓名”:“尼奥”,“年龄”:16岁,“标签”:“青少年”}, {“姓名”:“安娜”,“年龄”:9岁,“标签”:“孩子”} ] 我想编写一个函数来迭代列表c(并返回一个字典),以获得tag的值在字典列表中出现的次数。在这种情况下,它应该返回如下所示的字典:

假设我有以下词典列表:

c=[
{“姓名”:“汤姆”,“年龄”:10,“标签”:“孩子”},
{“姓名”:“马克”,“年龄”:35,“标签”:“成人”},
{“name”:“Pam”,“age”:70,“tag”:“very old”},
{“姓名”:“尼奥”,“年龄”:16岁,“标签”:“青少年”},
{“姓名”:“安娜”,“年龄”:9岁,“标签”:“孩子”}
]
我想编写一个函数来迭代列表
c
(并返回一个字典),以获得
tag
的值在字典列表中出现的次数。在这种情况下,它应该返回如下所示的字典:

tag_counts = dict()

for tag in c:
  if (tag['tag'] in tag_counts) == False:
    tag_counts[tag['tag']] = 1
  else:
    tag_counts[tag['tag']] += 1
f={“孩子”:2,“成人”:1,“非常老”:1,“青少年”:1}
如何做到这一点

from collections import Counter
print(Counter(el["tag"] for el in c))
计数器
是dict的子类,如果可以使用pandas,可以像dict

一样使用(个人认为这是解决此问题的一种过激手段)


您还可以创建一个空的dict并在初始dict上循环,如下所示:

tag_counts = dict()

for tag in c:
  if (tag['tag'] in tag_counts) == False:
    tag_counts[tag['tag']] = 1
  else:
    tag_counts[tag['tag']] += 1
这会给你

{'adult': 1, 'kid': 2, 'teenager': 1, 'very old': 1}

你试过密码吗?你遇到什么错误了吗?
{'adult': 1, 'kid': 2, 'teenager': 1, 'very old': 1}