Reputation: 19
If I have 2 dictionaries:
Total number of stops:
dict1: "a": 10, "b": 12 -->length
The stop number that having people waiting for the bus:
dict2: "a": [2, 2, 4, 7, 10], "b": [8, 4, 3, 2] --> position
For example: for route A there are 2 people at stop #2, 1 at stop #4, 1 at stop #7 and one at stop #10.
where I want to create a dictionary shows the total number of people waiting per each stop for each route like this:
dict3:{"a" = [0, 2, 0, 1, 0, 0, 1, 0, 0, 1], "b":[0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0]}
what show I do?
Upvotes: 0
Views: 38
Reputation: 108
dict1 = {"a": 10, "b": 12}
dict2 = {"a": [2, 2, 4, 7, 10], "b": [8, 4, 3, 2]}
result = {}
for k,v in dict1.items():
result[k] = [0] * v
for k,vs in dict2.items():
for v in vs:
result[k][v-1] += 1
print(result)
Result:
{'a': [0, 2, 0, 1, 0, 0, 1, 0, 0, 1], 'b': [0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0]}
Upvotes: 0
Reputation: 147196
You can use a Counter
to get the total count of passengers waiting at each stop from dict2
, then use a nested dictionary/list comprehension to turn those counts into an array of people waiting at each stop on each route:
from collections import Counter
dict1 = { "a": 10, "b": 12 }
dict2 = { "a": [2, 2, 4, 7, 10], "b": [8, 4, 3, 2] }
counts = { k : Counter(v) for k, v in dict2.items() }
dict3 = { k : [ counts[k][i] for i in range(1, dict1[k]+1) ] for k in dict2.keys() }
print(dict3)
Output:
{
'a': [0, 2, 0, 1, 0, 0, 1, 0, 0, 1],
'b': [0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0]
}
Upvotes: 1