+ 3

How to save changes in a dictionary in a loop?

I added key and value to my dictionary in a loop but I want to save the changes but we don't have a method like append in dictionary. My code: for i in range(1): a = input() a = a.split() for i in range(len(a)-1): b = {a[i+1]:a[0]} print(b) ______ Now for example: Sample input: hi hola hao Sample output: {'hola':'hi','hao':'hi'} _____ But my output is: {'hao':'hi'} Is there any method which I can save it to dictionary?

14th Oct 2021, 2:16 PM
Amirreza
Amirreza - avatar
8 Answers
+ 5
Your expectation can be written as : a = input().split() c =dict() for i in range(len(a)-1): c[a[i+1]]=a[0] print(c) Hope it helps..
14th Oct 2021, 2:27 PM
Jayakrishna 🇮🇳
+ 7
Amirreza Hashemi , i am not sure if it can help you, but you can use dict.update(...) to add a new key : value pair. here is a sample what you can do with it: https://code.sololearn.com/cQ0kf0HzeK36/?ref=app
14th Oct 2021, 5:27 PM
Lothar
Lothar - avatar
+ 1
Jayakrishna🇮🇳 my expected output is: Writing a number first! It will be th number of inputs For example: 2 hi hola hel hey hello hiya Output: {'hola' : 'hi' , 'hel' : 'hi' , 'hello' : 'hey' , 'hiya' : 'hey' }
14th Oct 2021, 4:06 PM
Amirreza
Amirreza - avatar
+ 1
Oh.. I did not checked code output.. You can run above correct working code in twice in a loop.. or define function with above working code and call twice or use like this with update() method : d={} for i in range(2): a = input().split() v=[] for i in a: v.append(i) c =dict() for i in range(len(v)-1): c[v[i+1]]=v[0] d.update(c) print(d) #i created global dictionary and added inner dictionary to global dictionary.
14th Oct 2021, 4:13 PM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 thx now It really helped me!
15th Oct 2021, 8:04 AM
Amirreza
Amirreza - avatar
+ 1
Lothar thank you I didn't know about it. Thanks for sharing good things
15th Oct 2021, 8:05 AM
Amirreza
Amirreza - avatar
0
Jayakrishna🇮🇳 Thanks. Now what if we change the range? v=[] for i in range(2): a = input().split() for i in a: v.append(i) c =dict() for i in range(len(v)-1): c[v[i+1]]=v[0] print(c) _______ In this case for example Range 2: Sample input: Hi hello Hey hola hiya Output: {'hello':'Hi','hola':'Hey', 'hiya':'Hey'} Do you have any solution for that ?
14th Oct 2021, 3:43 PM
Amirreza
Amirreza - avatar
0
The output is correct only... What is your expected output..? In previous code, you have only one iteration and so there is no need of loop so I removed it. If you want more than once, you can use loop..
14th Oct 2021, 3:59 PM
Jayakrishna 🇮🇳