简体   繁体   中英

Count the number of items in a dictionary inside a list as per the dictionary value

I have a dictionary inside a list structured like:

my_list = [
 {
     "id" : 1,
     "name" : "foo",
     "address" : "here"
 },
 {
     "id" : 2,
     "name" : "foo2",
     "address" : "there"
  },
 {
     "id" : 3,
     "name" : "foo3",
     "address" : "there"
  },
]

How do I get the total count of particular address? Say like i want to know how many people are from address "there". How do I do that??

Use len function along with 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
count = 0
for dictionary in my_list:
    if dictionary["address"] == "there":
        count+=1
print count

You can use sum function like following, Note that you need to loop over your dictionaries and check if the value of your target key is there ! :

sum(1 for d in my_list if d['address']=='there')

Demo :

>>> 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

You can use collections.Counter and list comprehensions

>>> from collections import Counter
>>> d = Counter([addr["address"] for addr in my_list])
>>> d["there"]
2

如果某些条目可能缺少address字段,则可以使用.get()方法。

sum(x.get('address') == "there" for x in my_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM