1

Considering the code snippet below -

list1 = [1,2,3,4]
list2 = [1,2,3,4]
list3 = ['a','b','c','d']
dct = dict(zip(zip(list1,list2),list3))
print(dct)

gives me,

{(1, 1): 'a', (2, 2): 'b', (3, 3): 'c', (4, 4): 'd'}

Now,

print(dct.keys())

gives me,

dict_keys([(1, 1), (2, 2), (3, 3), (4, 4)])

How can i access first element of the above list of keys? Something like -

dct.keys[0, 0] = 1
dct.keys[0, 1] = 1
dct.keys[1, 0] = 2
dct.keys[1, 2] = 2

and so on...

2 Answers2

1

Remember that a dict is unordered, and that dict.keys() may change order.

That said, to access the first element of a list, as you said, you can use list[element_index]. If the elemnt is an iterable, do that again!

So it would be

dct_keys = list(yourdict.keys())
dct_keys[0][0] = 1
dct_keys[0][1] = 1
dct_keys[1][0] = 2
dct_keys[1][1] = 2
WayToDoor
  • 1,180
  • 9
  • 24
  • 2
    Starting from 3.6, dictionaries _are_ ordered. – DYZ Dec 08 '18 at 23:13
  • @DYZ, In CPython only IIRC, but yup (and, TIL, in 3.7 they are [https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6]) – WayToDoor Dec 08 '18 at 23:15
  • As of 3.7, dictionaries are ordered as per definition of the language. – DYZ Dec 08 '18 at 23:16
0

You need to first convert the dct.keys() output to a list, and then the problem reduces to simple list-of-tuples indexing. To convert your .keys() output to a list, there are multiple available ways (check this out). Personally, I find using list comprehension as one of the simplest and most generic ways:

>>> [key for key in dct.keys()]
[(1, 1), (2, 2), (3, 3), (4, 4)]

And now simply index this list of tuples as:

>>> [key for key in dct.keys()][0][0]
1

Hope that helps.

bappak
  • 865
  • 8
  • 23
  • This sounds kinda bad performance wise, and less readable than just casting `dct.keys()` to a list with `list(dct.keys())` – WayToDoor Dec 08 '18 at 23:24