Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Wilfried Allico
2,495 PointsWhat do they mean by keys are sorted in Python?
What do they mean by keys are not sorted??
2 Answers
Cooper Runstein
11,851 PointsThis means that if you iterate through a dictionary (or a set) you won't get items out in the order they went in. If I create a dictionary:
dict = {
'key1': 1,
'key2': 2,
'key3': 3
}
And I iterate through it:
for key, values in dict.items():
print(key)
I might get:
key2
key1
key3
or I might get
key1
key3
key2
But I can't rely on the order the items are going to come out when I run through them, I just know that all of them will come up at some point in the iteration.
Dave StSomeWhere
19,870 PointsWhen using key value pairs in python you can never expect a specific order when processing.
So when executing the following code:
dict_example = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4',
'key5': 'value5'
}
# when looping you cannot expect a specific order or sort them - because you access them by key
for key, value in dict_example.items():
print('key is -->' + key)
print('value is -->' + value)
# access by key
print(dict_example['key3'])
hope that helps