Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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,我试图找出在下面的示例中,每个案例id会出现多少次email\u响应: json_obj = [{ 'case_id': 1000, 'type': 'email', 'customer_id': 42571, 'date': '2015-01-20', }, { 'case_id': 1000, 'type': 'email_response', 'customer_id': 42571, 'date': '2015-01

我试图找出在下面的示例中,每个案例id会出现多少次
email\u响应

json_obj = [{
    'case_id': 1000,
    'type': 'email',
    'customer_id': 42571,
    'date': '2015-01-20',
},
    {
    'case_id': 1000,
    'type': 'email_response',
    'customer_id': 42571,
    'date': '2015-01-21',
},
    {
    'case_id': 1021,
    'type': 'email',
    'customer_id': 88686,
    'date': '2015-01-24',
}]

因此,在这种情况下,答案将是
case\u id=1000的
1
case\u id=1021的
0
您可以创建另一个字典并像这样不断更新计数

>>> result = {}
>>> for obj in json_obj:
...     if obj['type'] == 'email_response':
...         result[obj['case_id']] = result.get(obj['case_id'], 0) + 1
...         
>>> result
{1000: 1, 1021: 0}
>>> result = {}
>>> for obj in json_obj:
...     result[obj['case_id']] = result.get(obj['case_id'], 0) + (obj['type'] == 'email_response')
...     
>>> result
{1000: 1, 1021: 0}
由于我们将
0
作为第二个参数传递,因此
dict.get
方法如果找不到要检索的键,将返回
0
,否则返回与键对应的实际值。你也可以这样做

>>> result = {}
>>> for obj in json_obj:
...     if obj['type'] == 'email_response':
...         result[obj['case_id']] = result.get(obj['case_id'], 0) + 1
...         
>>> result
{1000: 1, 1021: 0}
>>> result = {}
>>> for obj in json_obj:
...     result[obj['case_id']] = result.get(obj['case_id'], 0) + (obj['type'] == 'email_response')
...     
>>> result
{1000: 1, 1021: 0}

由于Python的布尔值是
int
的子类,
True
将是
1
False
将是
0
。因此,
(obj['type']='email\u response')
的结果将与
结果
字典中的
case\u id
的当前值相加。

太好了,我正试图熟悉Python中的列表和字典,但不知道存在这样的东西。谢谢