0

i want to print my 2nd key (Sally) but i keep getting the error!!!

ages = {"Demi":12, "Sally":15, "Micheala":22, "Joseph":19}
print(ages)

x = ages.keys()
print(x[2]) 
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    Yes, the `.keys()` of a dict is a `dict_keys` object, which doesn't support indexing like that. The thing is that, conceptually, dicts *do not have an order*, so asking for the "2nd" key *doesn't make sense*. (As it happens, the current implementation does maintain order internally, but that still doesn't help us here). – Karl Knechtel May 28 '20 at 22:59
  • You need to convert the `dict_keys` object to a list: `list(ages.keys())`. However, @KarlKnechtel is correct to point out that this is not a good practice. If you want order, use an ordered container like a list or tuple. – Amitai Irron May 28 '20 at 23:01
  • Or `collections.OrderedDict`. – Karl Knechtel May 28 '20 at 23:03
  • okay, understood...Thanks – Demilade Samuel May 28 '20 at 23:05

0 Answers0