[英]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.我正在遍历一个列表并尝试使用key/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.我知道我需要的是某种列表列表,虽然我让它适用于一个键有两个值的情况,但当我达到 3 个或更多时它会失败。
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>
.其中team2goals
是<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.它检查键 ( name
) 的实例是否存在,如果存在,它存储当前键值并创建值的字典,否则它只是添加一个新的键/对值。
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]
但这似乎只是开始嵌套字典,即[[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.您几乎拥有它,您需要为每个键创建一个列表,然后只需 append 时间戳。
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]]
?那么Dict[str, List[str]]
呢? This is easy using a defaultdict
这很容易使用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.基本上保存您提到的 2 个字符串对的列表。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.