Hi everyone I am fairly beginner at python and working on some sample exercises and learning to work with dictionary's . I have the following list provided and trying to get to the below output with the repeat 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]
To start off, I did this and got the results
for key in cast_list :
print(key['actor_id'], ':', key['understudy_num'])
98109 : 756
82793 : 392
71290 : 128
71290 : 407
98109 : 898
Now I am stuck as to how to get the actor_id to the corresponding understudy? I've started off with
#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
My logic: we want to look at the keys and values within cast_list... if the actor_id is not on the list, add it to new_list as a key with the value, else (if the key is already in new_list) append the appropriate key with the value.
A cleaner attempt to the logic.
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'
Any tips/links/solutions on where to go from here? I also got an error a few times saying TypeError: list indices must be integers or slices, not str but I thought my list is already in integer?
CodePudding user response:
You are really close! Your logic is sound, you're just mixing up how to use the different data structures:
- Lists are sequences of ordered items (values), there are no associated keys.
- Dicts are unordered collections of key-value pairs.
Here you're looking to associate a key (your actors) to multiple values (your understudies). To achieve what you want the best approach would be to create a dictionary:
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)
Example output:
>>> for k, v in new_dict.items():
... print(k, ":", v)
...
98109 : [756, 898]
82793 : [392]
71290 : [128, 407]
