-2

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}
Jakob Weisblat
  • 7,450
  • 9
  • 37
  • 65
Gokul1794
  • 137
  • 11

4 Answers4

1

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.

Rakholiya Jenish
  • 3,165
  • 18
  • 28
  • Bare `except` can catch more exceptions than was intended. Better provide the name of exception(s) (`KeyError` in this case). Or use `setdefault` as in @vks answer and avoid catching exceptions altogether. – Audrius Kažukauskas Jun 11 '15 at 09:04
0
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 ;)

user1269942
  • 3,772
  • 23
  • 33
0
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]
vks
  • 67,027
  • 10
  • 91
  • 124
  • Naming variable `dict` shadows built-in `dict` (dictionary constructor), choose some other name instead (e.g. `mydict`). It's also better to write `i not in mydict` instead of `not mydict.has_key(i)`, the latter is not available in Python 3 anymore. `mydict[i] = j + mydict[i]` can be shortened to `mydict[i] += j`. – Audrius Kažukauskas Jun 11 '15 at 08:59
0

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}
Abhijit
  • 62,056
  • 18
  • 131
  • 204