How to add repeating occurences of elements in two lists in python

119 views Asked by At

I have

filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]

Here,

 A=3, B=4 ,C=5, D =6, B=5. C=3

I want a dictionary like,

time_per_screen{A:3,B:9,C:8,D:6}
4

There are 4 answers

1
vks On BEST ANSWER
filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
mydict={}
for i,j in zip(filtered_symbolic_path,filtered_symbolic_path_times):
    if not mydict.has_key(i):
        mydict[i]=j
    else:
        mydict[i]=j+mydict[i]

You need to add if else to add the keys iteratively.

Or simply

filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
mydict={}
for i,j in zip(filtered_symbolic_path,filtered_symbolic_path_times):
    mydict.setdefault(i,0)
    mydict[i]=j+mydict[i]
2
user1269942 On
filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
time_per_screen = {}
for a, b in zip(filtered_symbolic_path, filtered_symbolic_path_times):
    time_per_screen[a] = b

edit: you should make sure that the 2 lists are the same length...I'll leave that for you to do. there's a neat tool called google...it's been around for a while now ;)

1
Rakholiya Jenish On

Try doing this:

filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
time_per_second = {}
for a, b in zip(filtered_symbolic_path, filtered_symbolic_path_times):
    try:
        time_per_screen[a] += b
    except KeyError:
        time_per_screen[a] = b

This will add value of a key if it already exist in dictionary else it will create a new key value pair.

0
Abhijit On

Counting tasks should be best handled with Counters. Create a counter and continue appending the pairs to the counter. Finally create a dictionary from the counter which is the output you are desiring for.

Example Code

from collections import Counter
for p, t in zip(filtered_symbolic_path, filtered_symbolic_path_times):
    c.update({p:t})

Sample Output

>>> dict(c)
{'A': 3, 'C': 8, 'B': 9, 'D': 6}