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:
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']