append()
is a method on the builtin list
type. Since the value associated with key1
is the builtin dict
type, you won't be able to use append()
to achieve this. There is another issue pertaining to your expected output:
{
1: 1,
3: 4,
1: 5,
}
You have two values for the key 1
in this dictionary. In python dictionaries, you can only have a single key. If you wanted to have multiple values for a particular key, there's a few ways to handle this (I would recommend reading up on Hash Tables: Collision Resolution).
For this example, given you were trying to use the append()
method, I'm going to assume you wanted to update the value stored to be a list containing [1, 5]
. In this case, one way of solving this would be with the following code.
dic = {
'key1': {1: 1},
'key2': {2: 5, 1: 1},
'key3': {2: 2, 1: 2},
}
key1_new_dict = {
1: [5],
3: [4],
}
for key, value in dic['key1'].items():
if key in key1_new_dict:
key1_new_dict[key].append(value)
else:
key1_new_dict[key] = [value]