Iterate a dict name in a loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Iterate a dict name in a loop

Hi everyone, I'm learning python for few days now and there is something I fail to do, and didnt find any answer on the web yet. I want to create multiple dict in a for loop: It looks like this: for i < 5: dict_name"i" = {"test": i} i +=1 What I want in result is: dict_name0 = {"test":0} dict_name1 = .... 1} ... dict_name4= ...4} I simplified the code there, but the real goal is to assign a full line of a file into a dict. Its working but with list: book_list = [] with open('testbook.txt','r') as indexing: for line in indexing: book_list = [line.strip() for line in indexing] Is there a way to change dynamically a name of a dict? Even with print command? for i < 5: print (dict_name"i" + ",") result wanted: dict_name0,dict_name1, ... ,dict_name4 #print all items of dict Thank you for your help. If you need more details just ask :)

20th Dec 2016, 3:45 PM
Flynn
Flynn - avatar
5 Answers
0
Well you can't dynamically create variable names. However one thing you may try, inside the loop create your dictionary and append it to a list. Thus creating a list of dictionaries.
20th Dec 2016, 5:30 PM
Rishi Anand
Rishi Anand - avatar
0
Hi, thank you for your answer. I see one problem with your solution. If you can't change the name of a dict into a loop, then they all will have the same name. I won't be able to call a specific dict[key]. your solution should looks like this: dict_name = {} dict_list = [] with open('testbook.txt','r') as indexing: for line in indexing: dict_name = [line.strip() for line in dexing] dict_list.append = dict_name So after that, I can call dict_list[x] but i can't call a specific dict as they all have the same name.
20th Dec 2016, 5:41 PM
Flynn
Flynn - avatar
0
Yes that is the issue, that you have to access the dictionaries with index of list. But think like this. Previously, your dictionaries didn't have any special name. Those names were created by the iterator value, i. This is all the same. Previously you had - dict_namei Now you have - dict_list[i] Additionally a list has lots of special methods like iteration, count, etc that aren't available with isolated variables. I'm not saying this is exactly what you want, but you can adjust your problems demand like this very beautifully. And that's the essence of programming
20th Dec 2016, 5:48 PM
Rishi Anand
Rishi Anand - avatar
0
And yes you will be able to call a specific dict[key] too. Like dict_list[i][key]
20th Dec 2016, 5:55 PM
Rishi Anand
Rishi Anand - avatar
0
Ok im gonna try it and come back to you for the results. Thank you again Rishi.
20th Dec 2016, 6:02 PM
Flynn
Flynn - avatar