Can anyone explain how this works? (dictionaries) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can anyone explain how this works? (dictionaries)

So I have written a code that took me awhile to write but in the end, after thinking about it, i honestly dont understand HOW a part of it works. The program would ask for name, age, weight, and height and put them in a file, with no limit to how many people to enter. Its written like this: age_dic = {} height_dic = {} weight_dic = {} file = open('test.txt', 'w') num = input() #enters how many people they plan to enter for x in range(num): ..... #assigns name, age, weight, and height variables age_dic[name] = age weight_dic[name] = weight height_dic[name] = height for key, value in age_dic.items(): age_des = "".join([key, ":\nAge: ", str(value)]) for key, value in height_dic.items(): height_des = "".join(["\nHeight: ", str(value)]) for key, value in weight_dic.items(): weight_des = "".join(["\nWeight: ", str (value)]) des = "".join([age_des, height_des, weight_des]) file.write(des + "\n\n") file.close() To clarify what im asking, when I enter 2 persons, they both appear on the file as intended, but what i am having trouble understanding is this: When it comes down the for loop for the second person, it adds to the dictionaries (where there are now two key:value pairs, which is proven when i print the dictionaries out in the end) but the value of the variable "des" is updated to the second person (if you print out des as the end, it would display the info of the second person, not the first). How does python know to only assign the second key value pair to the variable? Ps, sorry if i make no sense

28th Oct 2016, 12:43 AM
Alex
Alex - avatar
2 Answers
+ 5
Try printing des right after its assignment in the loop (so that it prints all the values it takes), rather than printing it after the loop (in which case it will only print the last value it took).
28th Oct 2016, 10:36 AM
Zen
Zen - avatar
+ 1
From my understanding each of the loops will execute depending how many entries you have in the dictionary. Because you use = sign when the loop run age_des becomes key, ":\nAge: ", str(value) for the first entry then executes again and overwrites the previous content of the variable. However it might not be the case for large dictionaries as the dictionary type is unordered. By the way you can make a list for each person that will hold name, age, weight, and height and assign that to one key in the dictionary. myDict = {} myDict[key] = myList Working with one dictionary should be easier. If you need clarification just ask :).
28th Oct 2016, 9:34 AM
Bartosz Jurus
Bartosz Jurus - avatar