I am trying to add a list of value for a key. I use the following lines :
d = dict()
for i in range(5):
d['key'].append(i)
But I get the error : KeyError: 'key'
The expected output is : {'key' : [0,1,2,3,4]}
How to fix this error ?
CodePudding user response:
You can't append to a nonexistent list. Initialize d['key']
first.
d = {'key': []}
for i in range(5):
d['key'].append(i)
CodePudding user response:
You can use defaultdict
to create automatically an object for a missing key, in this case an empty list.
from collections import defaultdict
d = defaultdict(list)
for i in range(5):
d['key'].append(i)
print(d)
# defaultdict(<class 'list'>, {'key': [0, 1, 2, 3, 4]})
CodePudding user response:
Python has no way to know that the values for the key key
are a list. First you should initialize the key and then append the values like:
d = dict()
d['key'] = []
for i in range(5):
d['key'].append(i)
print(d)
# {'key': [0, 1, 2, 3, 4]}
CodePudding user response:
Given a dict that might contain 'key'
, I would write this with a try/except over KeyError
and start the list if it doesn't exist
for i in range(5):
try:
d['key'].append(i)
except KeyError: # key not in d (yet)
d['key'] = [i] # start a new list
CodePudding user response:
First of all what are you trying to accomplish here? If you want to create a list value for that key you should do it like
d['key'] = [0, 1, 2, 3, 4]
Anyway, the problem in your code is that you are trying to append a value in a list that does not exist. A solution to your problem could be
d = dict()
for i in range(5):
if 'key' not in d.keys():
d['key'] = []
else:
d['key'].append(i)
CodePudding user response:
Just another unmentioned way, for the one liners:
d = {'key' : [i for i in range(5)]}
This is called comprehension in python: python comprehension
CodePudding user response:
d = {}
xkey =1
i=[]
for x in range(5):
i.append(x)
d[xkey] = i
print(d)
The result
{1: [0, 1, 2, 3, 4]}