Skip to content

Commit d9b3ddf

Browse files
Merge pull request #386 from danielquinn/gh-pages
Fix dictionary ordering issues
2 parents c138c99 + 7a3a567 commit d9b3ddf

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

python/lesson3/tutorial.md

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -277,13 +277,20 @@ manageable parts. Thankfully, Python has you covered with `.keys()`,
277277
"Davos": "+244562726258"
278278
}
279279
>>> print(my_phone_book.keys())
280-
dict_keys(['Davos', 'Cersei', 'Brienne', 'Arya'])
280+
dict_keys(['Arya', 'Brienne', 'Cersei', 'Davos'])
281281

282282
>>> print(my_phone_book.values())
283-
dict_values(['+3206785246863', '+14357535455', '+244562726258', '+4407485376242'])
283+
dict_values(['+4407485376242', '+3206785246863', '+14357535455', '+244562726258'])
284284

285285
>>> print(my_phone_book.items())
286-
dict_items([('Brienne', '+3206785246863'), ('Cersei', '+14357535455'), ('Davos', '+244562726258'), ('Arya', '+4407485376242')])
286+
dict_items([('Arya', '+4407485376242'), ('Brienne', '+3206785246863'), ('Cersei', '+14357535455'), ('Davos', '+244562726258')])
287+
288+
> **Important**: dictionaries are *unordered*, which means that while it may
289+
> seem reasonable that you've defined `my_phone_book` above with the keys
290+
> ordered alphabetically, *that's not now how Python stores them*, so the
291+
> results above may differ in order from your output. Typically if you need
292+
> your dictionary to be ordered, you'll use a list of lists, or an
293+
> `OrderedDict` (a topic for another day).
287294
288295
As you can see, `.keys()` and `.values()` do what you'd expect: they return the
289296
keys and values respectively. You may have noticed however that rather than a
@@ -293,19 +300,19 @@ anything with them other than read them as a complete entity, you'll have to
293300
cast them as a list:
294301

295302
>>> print(list(my_phone_book.values()))
296-
['+3206785246863', '+14357535455', '+244562726258', '+4407485376242']
303+
['+4407485376242', '+3206785246863', '+14357535455', '+244562726258']
297304

298-
>>> print(list(my_phone_book.values())[2])
305+
>>> print(list(my_phone_book.values())[3])
299306
'+244562726258'
300307

301308
The last one there, `.items()` is interesting. It returns all of the data in
302309
your dictionary, but dumps it out as `dict_items` which is a sort of *tuple of
303310
tuples*. This allows you to reference your dictionary with list syntax:
304311

305-
>>> print(tuple(my_phone_book.items())[0])
312+
>>> print(tuple(my_phone_book.items())[1])
306313
('Brienne', '+3206785246863')
307314

308-
>>> print(tuple(my_phone_book.items())[0][1])
315+
>>> print(tuple(my_phone_book.items())[1][1])
309316
'+3206785246863'
310317

311318
Truth be told though, you probably won't be accessing these values directly

0 commit comments

Comments
 (0)