@@ -277,13 +277,20 @@ manageable parts. Thankfully, Python has you covered with `.keys()`,
277
277
"Davos": "+244562726258"
278
278
}
279
279
>>> print(my_phone_book.keys())
280
- dict_keys(['Davos ', 'Cersei ', 'Brienne ', 'Arya '])
280
+ dict_keys(['Arya ', 'Brienne ', 'Cersei ', 'Davos '])
281
281
282
282
>>> print(my_phone_book.values())
283
- dict_values(['+3206785246863 ', '+14357535455 ', '+244562726258 ', '+4407485376242 '])
283
+ dict_values(['+4407485376242 ', '+3206785246863 ', '+14357535455 ', '+244562726258 '])
284
284
285
285
>>> 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).
287
294
288
295
As you can see, ` .keys() ` and ` .values() ` do what you'd expect: they return the
289
296
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
293
300
cast them as a list:
294
301
295
302
>>> print(list(my_phone_book.values()))
296
- ['+3206785246863 ', '+14357535455 ', '+244562726258 ', '+4407485376242 ']
303
+ ['+4407485376242 ', '+3206785246863 ', '+14357535455 ', '+244562726258 ']
297
304
298
- >>> print(list(my_phone_book.values())[2 ])
305
+ >>> print(list(my_phone_book.values())[3 ])
299
306
'+244562726258'
300
307
301
308
The last one there, ` .items() ` is interesting. It returns all of the data in
302
309
your dictionary, but dumps it out as ` dict_items ` which is a sort of * tuple of
303
310
tuples* . This allows you to reference your dictionary with list syntax:
304
311
305
- >>> print(tuple(my_phone_book.items())[0 ])
312
+ >>> print(tuple(my_phone_book.items())[1 ])
306
313
('Brienne', '+3206785246863')
307
314
308
- >>> print(tuple(my_phone_book.items())[0 ][1])
315
+ >>> print(tuple(my_phone_book.items())[1 ][1])
309
316
'+3206785246863'
310
317
311
318
Truth be told though, you probably won't be accessing these values directly
0 commit comments