Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count each value occurrences while having the same value of another key

This is a list I have:

list1 = [
    {'city': 'Tehran', 'street': 'Ferdowsi'},
    {'city': 'Tabriz', 'street': 'Imam'},
    {'city': 'Sari', 'street': 'Qaran'},
    {'city': 'Tehran', 'street': 'Enghelab'},
    {'city': 'Tabriz', 'street': 'Imam'},
    {'city': 'Tehran', 'street': 'Kan'},
    {'city': 'Tehran', 'street': 'Kan'},
    {'city': 'Sari', 'street': 'Nader'},
    {'city': 'Sari', 'street': 'Nader'},
]

I’m going to both have count each city has how many streets with the equal name, and have a list of them, like the following as expected output:

Tehran 1 Ferdowsi
Tabriz 2 Imam
Sari 1 Qaran
Tehran 1 Enghelab
Tehran 2 Kan
Sari 2 Nader

And also this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Tehran [Ferdowsi]
Tabriz [Imam, Imam]
Sari [Qaran]
Tehran [Enghelab]
Tehran [Kan, Kan]
Sari [Nader, Nader]

I tried this, but show all streets related to one city:

from collections import defaultdict

cities = defaultdict(list)
for name in list1:
    cities[name['city']].append(name['street'])

Current output:

>>> for x in cities: x, cities[x]
...
('Tehran', ['Ferdowsi', 'Enghelab', 'Kan', 'Kan'])
('Tabriz', ['Imam', 'Imam'])
('Sari', ['Qaran', 'Nader', 'Nader'])

And also I know this counts how many times each street is repeated:

from collections import Counter
counts = Counter(row["street"] for row in list1)

Its current output:

>>> for x in counts: x, counts[x]
...
('Ferdowsi', 1)
('Imam', 2)
('Qaran', 1)
('Enghelab', 1)
('Kan', 2)
('Nader', 2)

But the issue is I’m not sure and what to search to have what I’m looking for.

>Solution :

You just need to include the city in the Counter:

counts = Counter((row['city'], row["street"]) for row in list1)
>>> dict(counts)
{('Tehran', 'Ferdowsi'): 1,
 ('Tabriz', 'Imam'): 2,
 ('Sari', 'Qaran'): 1,
 ('Tehran', 'Enghelab'): 1,
 ('Tehran', 'Kan'): 2,
 ('Sari', 'Nader'): 2}

Then you can get the output you want like this for example (all together):

for (city, street), count in counts.items():
    print(city, count, street, [street]*count)
Tehran 1 Ferdowsi ['Ferdowsi']
Tabriz 2 Imam ['Imam', 'Imam']
Sari 1 Qaran ['Qaran']
Tehran 1 Enghelab ['Enghelab']
Tehran 2 Kan ['Kan', 'Kan']
Sari 2 Nader ['Nader', 'Nader']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading