+ 1
how to add a key to a dictionary? Eg: {0:10, 1:20} Expected output:{0:10, 1:20, 2:30}
9 Answers
+ 6
d={}
d[1]=10
d[2]=20
d[3]=30
print(d)
or:
d={}
for i in range(1,4):
d[i]=i*10
print(d)
or:
d=dict((i,i*10) for i in range(1,4))
print(d)
+ 5
add as in the math operator?
+ 5
the range was just an example
the nice thing about python dictionary is that the key-value pair is added if the key does not exists already
if key does exists, then the value of it will be updated
d={} # create new empty dictionary
d["hello"]="world"
print(d)
{"hello": "world"}
d["foo"]="bar"
print(d)
{"hello": "world", "foo": "bar"}
d["hello"]=42 # updates value of key "hello"
print(d)
{"hello": 42, "foo": "bar"}
+ 5
that not gonna work
dictionary works by assigning value to a key
dic={}
dic[0]=10 # this create a key-value pair in the dictionary where the key is whatever inside the [ ] and the value is on the right side of =
+ 1
okay š got it
thanks a lotš
0
if use the add functionļ¼
0
can i just type it outļ¼
0
and how about if the dictionary value is not in rangeļ¼
0
so if i write like this is okay or notļ¼
dic=ļ½ļ½
dic=ļ½0:10ļ½
dic=ļ½1:20ļ½
dic=ļ½2:30ļ½
printļ¼dicļ¼