如何在字典列表中追加到嵌套列表?

时间:2020-05-23 10:58:05

标签: python-3.8

我知道这个问题过去已经得到回答,但是我无法归纳出解决问题的方法,可能是因为我不太了解这种行为的根本原因。

我有以下列表:

matches = [
{'name': 'gm1', 'odds': {'full time': {'3way': []}}},
{'name': 'gm2', 'odds': {'full time': {'3way': []}}},
{'name': 'gm2', 'odds': {'full time': {'3way': []}}},
]

当我跑步时:

for match in matches:
    match['odds']['full time']['3way'].append({'match_index': matches.index(match)})

我希望得到:

[{'name': 'gm1', 'odds': {'full time': {'3way': [{'match_index': 0}]}}},
{'name': 'gm2', 'odds': {'full time': {'3way': [{'match_index': 1}]}}},
{'name': 'gm2', 'odds': {'full time': {'3way': [{'match_index': 2}]}}}]

我得到:

[{'name': 'gm1', 'odds': {'full time': {'3way': [{'match_index': 0}, {'match_index': 1}, {'match_index': 2}]}}},
{'name': 'gm2', 'odds': {'full time': {'3way': [{'match_index': 0}, {'match_index': 1}, {'match_index': 2}]}}},
{'name': 'gm2', 'odds': {'full time': {'3way': [{'match_index': 0}, {'match_index': 1}, {'match_index': 2}]}}}]

如果我在IDE中手动生成列表,则会使混乱达到预期效果,但是当从文件中加载相同列表时,会产生不需要的结果。

1 个答案:

答案 0 :(得分:0)

我不知道这是否是问题所在,但您没有添加逗号来分隔匹配列表中的元素:

matches=[{'name': 'gm1', 'odds': {'full time': {'3way': []}}},{'name': 'gm2', 'odds': {'full time': {'3way': []}}},{'name': 'gm3', 'odds': {'full time': {'3way': []}}}]

我跑了你之后,我得到了正确的结果:

>>> for match in matches:
...     match['odds']['full time']['3way'].append({'index': matches.index(match)})

输出:

>>> matches
[{'name': 'gm1', 'odds': {'full time': {'3way': [{'index': 0}]}}}, {'name': 'gm2', 'odds': {'full time': {'3way': [{'index': 1}]}}}, {'name': 'gm3', 'odds': {'full time': {'3way': [{'index': 2}]}}}]