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

时间:2020-05-26 23:41:23

标签: python dictionary

我正在遍历一个列表并尝试创建具有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]

有没有办法做我想做的事?

3 个答案:

答案 0 :(得分:1)

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

尝试一下:

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

答案 1 :(得分:1)

Dict[str, List[str]]呢?使用defaultdict

很容易
from collections import defaultdict

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

答案 2 :(得分:0)

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

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

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

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

代码:

byte

收益:

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