+ 2
Dictionary key-value pair sort order changes each time with user input
The attached code should count the total number of vowels in a string provided by user input, as well as count the number of each individual vowel in the said string. I store the vowel and number of vowel pairs in a dictionary. But it seems that order in which the dictionary entries are stored is almost random, as it changes each time I test with a different input. Does anyone have an idea what causes this? Thank you. https://code.sololearn.com/c3YGAgVA3ewF/?ref=app
5 ответов
+ 3
Dictionary behavior in the background of python is sorted in a way that isn't apparent to the programmer. It's easier to say that key order in a dictionary is not a guarantee like it is with lists or tuples. So when accessing the dictionary, you have to know what key you're looking for, otherwise you'll get a key error.
But if say you don't know what's inside your dictionary, then you'll have to use a loop to iterate through the keys, much the same way you would a list.
The random sorting of the keys is not important though, the primary use of of the dictionary is to have list of keys that are unique from each other.
If for some reason you aren't sure what you're adding, a loop must be used to iterate through it, as mentioned.
+ 1
@Agnius Bartninkas
Correct, the dictionary won't output in alphabetical or numerical order. You'll have to grab the keys and sort them yourself outside the dictionary. This can be solved easily using a list comprehension. Or the regular way with for or while loops. The first way is just laz..err..more efficient.
0
What is the output of this code?
>>> x = 3
>>> num = 17
>>> print(num % x)
0
@Sapphire Thank you. I do know the contents of my dictionary. What I am trying to do is print its key-value pairs in alphabetical order (my keys are vowels and the values are the number of instances each of that vowel has appeared in a given string). But I assume it has nothing to do with how I handle the dictionary. I will think of a way to sort my output. Thank you once again for a prompt and detailed answer.
0
@shojaei: the output is 2.