我在列表中有一个字典,结构如下:
my_list = [
{
"id" : 1,
"name" : "foo",
"address" : "here"
},
{
"id" : 2,
"name" : "foo2",
"address" : "there"
},
{
"id" : 3,
"name" : "foo3",
"address" : "there"
},
]
如何获取特定地址的总数?比如我想知道有多少人来自地址"那里"。我该怎么办?
答案 0 :(得分:2)
使用len函数和list_comprehension。
>>> my_list = [
{
id : 1,
'name' : 'foo',
'address' : 'here'
},
{
id : 2,
'name' : 'foo2',
'address' : 'there'
},
{
id : 3,
'name' : 'foo3',
'address' : 'there'
},
]
>>> len([x for x in my_list if x['address'] == 'there'])
2
答案 1 :(得分:1)
count = 0
for dictionary in my_list:
if dictionary["address"] == "there":
count+=1
print count
答案 2 :(得分:1)
您可以使用sum
函数,如下所示,注意,您需要遍历字典并检查目标键的值是否为there
! :
sum(1 for d in my_list if d['address']=='there')
演示:
>>> my_list = [
... {
... 'id' : 1,
... 'name' : 'foo',
... 'address' : 'here'
... },
... {
... 'id' : 2,
... 'name' : 'foo2',
... 'address' : 'there'
... },
... {
... 'id' : 3,
... 'name' : 'foo3',
... 'address' : 'there'
... },
... ]
>>> sum(1 for d in my_list if d['address']=='there')
2
答案 3 :(得分:1)
您可以使用collections.Counter和列表推导
>>> from collections import Counter
>>> d = Counter([addr["address"] for addr in my_list])
>>> d["there"]
2
答案 4 :(得分:1)
如果某些条目可能缺少address
字段,您可以使用.get()
方法。
sum(x.get('address') == "there" for x in my_list)