解析列表中的 Python 字典

Parsing a Python Dictionary within a list

大家好,我是 python 的新手,正在做一些示例练习并学习使用字典的 .我提供了以下列表并尝试通过重复 understudy_num.

获得以下输出
cast_list = [{'actor_id' : 98109, 'understudy_num' : 756},
    {'actor_id' : 82793, 'understudy_num' : 392},
    {'actor_id' : 71290, 'understudy_num' : 128},
    {'actor_id' : 71290, 'understudy_num' : 407},
    {'actor_id' : 98109, 'understudy_num' : 898},  ]

98109 : [759, 898]
82793 : [392]
71290 : [128, 407]

首先,我这样做并得到了结果

for key in cast_list :
    print(key['actor_id'], ':', key['understudy_num'])

98109 : 756
82793 : 392
71290 : 128
71290 : 407
98109 : 898

我现在很纠结怎么把actor_id给到相应的替补?我从

开始
#print("GIVEN:" , cast_list ) #just to print original

new_list= []
for key in cast_list:
    if key['actor_id'] not in new_list:
        new_list[key['actor_id']] = [key]
    else: 
        new_list[key['understudy_num']].apend(key)
    print(key['actor_id'], ':', '[', key['understudy_num'] , ']')

ERROR: list assignment index out of range

我的逻辑:我们想查看 cast_list 中的键和值...如果 actor_id 不在列表中,将其作为键添加到 new_list带有值,否则(如果键已经在 new_list 中)将相应的键附加到值。

更清晰的逻辑尝试。

new_list= []
for dict in cast_list:
    for key,value in dict.items():
        if key in new_list.keys():
            new_list[key].append(value)
        else:    
            new_list[key]=[value]
    
print(new_list)

AttributeError: 'list' object has no attribute 'keys'

任何 tips/links/solutions 从这里到哪里去?我也有几次出错说 TypeError: list indices must be integers or slice, not str 但我认为我的列表已经是整数了?

你真的很亲近!你的逻辑是合理的,你只是混淆了如何使用不同的数据结构:

  • 列表是有序项目(值)的序列,没有关联的键。
  • 字典是键值对的无序集合。

在这里,您希望将一个键(您的 演员 )与多个值(您的 学生 )相关联。 要实现你想要的,最好的方法是创建一个字典:

new_dict = {}
for d in cast_list:
    actor =  d["actor_id"]
    understudy = d["understudy_num"]

    if actor not in new_dict:
        new_dict[actor] = [understudy]
    else:
        new_dict[actor].append(understudy)

示例输出:

>>> for k, v in new_dict.items():
...     print(k, ":", v) 
... 
98109 : [756, 898]
82793 : [392]
71290 : [128, 407]