2

I'm looping through a list and trying to create a dictionary with key/pair values, the problem is that as I'm looping through the list, I may find duplicate instances of a key, in which case I'd like to add another pair. I know what I need is some sort of list of lists, and while I got it working for instances where there are two values of a pair for a key, it fails when I get to 3 or more.

This is my current code:

team2goals = {}
<loop through list>
    timestamp = xValue
    if name in team2goals:
        temp = team2goals[name]
        temp = {temp,timestamp}
        team2goals[name] = temp
    else:
        team2goals[name] = timestamp

Where team2goals is a dictionary of <str>,<str>. It checks to see if an instance of the key (name) exists, and if it does it stores the current key value and creates a dictionary of the values, otherwise it just adds a new key/pair value.

I tried something like:

 tempT = team1goals[name]
 temp = []
 temp.append(tempT)
 temp.append(timestamp)
 team1goals[name] = temp

But that just seemed to start nesting dictionaries i.e. [[timestamp,timestamp2],timestamp3]

Is there a way to do what I'm trying?

martineau
  • 119,623
  • 25
  • 170
  • 301
AndyReifman
  • 1,459
  • 4
  • 18
  • 34
  • Just wondering if you have searched for your question in stack overflow before asking? Possible Duplicate: https://stackoverflow.com/questions/5378231/list-to-dictionary-conversion-with-multiple-values-per-key – Akib Rhast May 26 '20 at 23:49
  • Does this answer your question? [list to dictionary conversion with multiple values per key?](https://stackoverflow.com/questions/5378231/list-to-dictionary-conversion-with-multiple-values-per-key) – Akib Rhast May 26 '20 at 23:50

3 Answers3

1

You almost had it, you need to create a list for each key and then just append the timestamps.

Try this:

team2goals = {}
<loop through list>
    timestamp = xValue
    if name not in team2goals:
        team2goals[name] = []
    team2goals[name].append(timestamp)
fafl
  • 7,222
  • 3
  • 27
  • 50
  • That's it exactly, thank you so much. I always get so turned around when dealing with python dicts and tend to over complicate everything. – AndyReifman May 26 '20 at 23:50
  • @Eabryt This is still overcomplicating it. Use a `defaultdict`, then you don't need to worry about checking for membership first. – Dan May 27 '20 at 00:19
  • @Dan i always forget what the parameter of defaultdict does. defaultdict(0) fills non-existing keys with zero, but defaultdict(list) uses the parameter as a function to create new default values. This overloaded behavior confuses me, so I prefer to write it by hand. – fafl Jun 14 '20 at 10:41
1

What about a Dict[str, List[str]]? This is easy using a defaultdict

from collections import defaultdict

team_to_goals = defaultdict(list)
<loop>:
    team_to_goals[name].append(x_value)
Dan
  • 45,079
  • 17
  • 88
  • 157
0

A couple of things you can do. If you have multiple entries for the same key value, you should use the one key value, but keep a list of results. If each result has multiple components, you could keep them in a sub-list or a tuple. for your application I would suggest:

key : list(tuples( data, timestamp))

Basically hold a list of pairs of the 2 strings you mention.

Also, default dictionary is good for this because it will create new list items in a dictionary as the 'default item'.

Code:

from collections import defaultdict

# use default dictionary here, because it is easier to initialize new items

team_goals = defaultdict(list)   # just list in here to refer to the class, not 'list()''

# just for testing
inputs = [  ['win big', 'work harder', '2 May'], 
            ['be efficient', 'clean up', '3 may'],
            ['win big', 'be happy', '15 may']]

for key, idea, timestamp in inputs:
    team_goals[key].append((idea, timestamp))

print(team_goals)
for key in team_goals:
    values = team_goals[key]
    for v in values:
        print(f'key value: {key} is paired with {v[0]} at timestamp {v[1]}')

Yields:

defaultdict(<class 'list'>, {'win big': [('work harder', '2 May'), ('be happy', '15 may')], 'be efficient': [('clean up', '3 may')]})

key value: win big is paired with work harder at timestamp 2 May
key value: win big is paired with be happy at timestamp 15 may
key value: be efficient is paired with clean up at timestamp 3 may
[Finished in 0.0s]
AirSquid
  • 10,214
  • 2
  • 7
  • 31
  • Maybe I misread your post based on other solutions. I thought you wanted to store a pair of strings for each key value.... Anyhow, maybe some nuggets to use. – AirSquid May 26 '20 at 23:59