+ 1

how to add a key to a dictionary? Eg: {0:10, 1:20} Expected output:{0:10, 1:20, 2:30}

17th Apr 2017, 10:12 AM
Chilllittle
Chilllittle - avatar
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)
17th Apr 2017, 10:14 AM
Burey
Burey - avatar
+ 5
add as in the math operator?
17th Apr 2017, 10:20 AM
Burey
Burey - avatar
+ 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"}
17th Apr 2017, 10:30 AM
Burey
Burey - avatar
+ 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 =
17th Apr 2017, 10:43 AM
Burey
Burey - avatar
+ 1
okay 👌 got it thanks a lot😁
17th Apr 2017, 12:26 PM
Chilllittle
Chilllittle - avatar
0
if use the add function?
17th Apr 2017, 10:18 AM
Chilllittle
Chilllittle - avatar
0
can i just type it out?
17th Apr 2017, 10:22 AM
Chilllittle
Chilllittle - avatar
0
and how about if the dictionary value is not in range?
17th Apr 2017, 10:24 AM
Chilllittle
Chilllittle - avatar
0
so if i write like this is okay or not? dic={} dic={0:10} dic={1:20} dic={2:30} print(dic)
17th Apr 2017, 10:35 AM
Chilllittle
Chilllittle - avatar