0

code not working

Hello I am continuing to learn with "crash course in python" I am at the section on dictionary and how to put dictionary into list, and iterate through them. I started by creating a list and dictionary, and wrote a code to insert the dictionary in the list, worked fine. Then I tried to modify the value of one key, in some of the dictionary. dic = { 'a' : 1, 'b' : 2, 'c' : 4, 'd' : 5, } list1 = ['f','e','c','n'] print(list1) print(len(list1)) x = 0 while x < 7: if x <= len(list1) - 1: list1[x] = dic x += 1 else: list1.append('vv') x +=1 print(list1) for dic in list1[:2]: dic['c'] = 'wistiti' print(list1) I wrote it exactly like in the book but does not work. With this version the key 'c' is changed to the specify value, in EVERY dictionary in my list. And if I write list1[1] list1[:] I get this error message File "c:....../Crash course/dictionaryloop.py", line 21, in <module> dic['c'] = 'wistiti' TypeError: 'str' object does not support item assignment Any input on what I am doing wrong?

5th Dec 2019, 6:37 AM
nicolas seespan
nicolas seespan - avatar
7 ответов
+ 10
nicolas seespan your posted code is working fine. Can you please elaborate what you want to do with your code or you are trying something else in this code https://code.sololearn.com/c1BmL65MMOCa/?ref=app
5th Dec 2019, 9:15 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 2
Post your whole code, maybe some-one can help you if they can play with it
5th Dec 2019, 8:43 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Tap the " insert code button " and attach your whole code with us then only we will be able to find the problem
5th Dec 2019, 8:50 AM
Arsenic
Arsenic - avatar
+ 1
My code 2019/12/05 16:05 dic = { 'a' : 1, 'b' : 2, 'c' : 4, 'd' : 5, } list1 = ['f','e','c','n'] print(list1) print(len(list1)) x = 0 while x < 7: if x <= len(list1) - 1: list1[x] = dic x += 1 else: list1.append('vv') x +=1 print(list1) for dic in list1[:2]: dic['c'] = 'wistiti' print(list1)
5th Dec 2019, 9:06 AM
nicolas seespan
nicolas seespan - avatar
+ 1
Sorry but I did not find any "insert your code " button.
5th Dec 2019, 9:06 AM
nicolas seespan
nicolas seespan - avatar
+ 1
Hello After the first part of the code, the list list1 has four dictionary in position, 0, 1 , 2 and 3. I want to change the value of the key 'c' to 'wistitié , but only for the dictionary in position 0 and 1 ( hence I wrote :2 ), but the value is changed in all the dictionaries.
5th Dec 2019, 9:25 AM
nicolas seespan
nicolas seespan - avatar
+ 1
See if this is what you were after https://code.sololearn.com/cexXWQ3mwwvA/?ref=app
6th Dec 2019, 9:07 PM
Rik Wittkopp
Rik Wittkopp - avatar