+ 1
how to add a key to a dictionary? Eg: {0:10, 1:20} Expected output:{0:10, 1:20, 2:30}
9 Respostas
+ 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)