繁体   English   中英

处理每个键具有多个值的字典

[英]Handling a dictionary with multiple values per key

我正在遍历一个列表并尝试使用key/pair值创建一个字典,问题是当我遍历列表时,我可能会发现一个键的重复实例,在这种情况下我想添加另一对。 我知道我需要的是某种列表列表,虽然我让它适用于一个键有两个值的情况,但当我达到 3 个或更多时它会失败。

这是我当前的代码:

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

其中team2goals<str>,<str>的字典。 它检查键 ( name ) 的实例是否存在,如果存在,它存储当前键值并创建值的字典,否则它只是添加一个新的键/对值。

我试过类似的东西:

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

但这似乎只是开始嵌套字典,即[[timestamp,timestamp2],timestamp3]

有没有办法做我正在尝试的事情?

您几乎拥有它,您需要为每个键创建一个列表,然后只需 append 时间戳。

尝试这个:

team2goals = {}
<loop through list>
    timestamp = xValue
    if name not in team2goals:
        team2goals[name] = []
    team2goals[name].append(timestamp)

那么Dict[str, List[str]]呢? 这很容易使用defaultdict

from collections import defaultdict

team_to_goals = defaultdict(list)
<loop>:
    team_to_goals[name].append(x_value)

你可以做几件事。 如果同一键值有多个条目,则应使用一个键值,但保留结果列表。 如果每个结果都有多个组件,您可以将它们保存在子列表或元组中。 对于您的应用程序,我建议:

键:列表(元组(数据,时间戳))

基本上保存您提到的 2 个字符串对的列表。

此外,默认字典对此很有用,因为它将在字典中创建新的列表项作为“默认项”。

代码:

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]}')

产量:

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.

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