简体   繁体   中英

Handling a dictionary with multiple values per key

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 ie [[timestamp,timestamp2],timestamp3]

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

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)

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM