0

Sorry this is probably very simple, but I suspect I'm wording the question wrong from inexperience so I haven't been able to find the answer anywhere.

I have a dictionary, e.g.:

dict = {1: 'a', 2: 'b'}

I want to select specific values within the dictionary from knowing only their position in the dictionary.

For example I want to print the first key, and all I know about the key is that it's the first key in the dictionary, not its actual name to call on.

I am trying:

dict[0][0]

And I'm expecting this to output 1, the first key in the dictionary - but I'm not experienced in python so I'm not sure how to get this working?

DN1
  • 234
  • 1
  • 13
  • 38
  • 1
    Depending on your python version, the dictionary may or may not be ordered by insertion order. I think it is guaranteed for python 3.7+ and accidentally the case for 3.5&3.6. Dictionaries don't support direct indexing though – PirateNinjas May 07 '21 at 10:16
  • Indexing was the word I needed to know to do a much better job googling this problem - thank you for this!! Good to know I can't do it directly so I can try something else, thanks! – DN1 May 07 '21 at 10:19

4 Answers4

1

This is probably what you were looking for.

Note this is for Python 3.7 and forward.

d = {1: 'a', 2: 'b'} # dict is a bad variable name! don't do it! it overrides a built-in!
d_keys = list(d.keys())
first_value = d[d_keys[0]]
Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • 1
    Thank you for this, didn't realise about the dict thing either - will keep that in mind going forward, thanks! – DN1 May 07 '21 at 10:32
1

Dictionaries cannot be used like lists, in that you cannot refer to their position. However, you can use something like this to get the keys from your dictionary:

my_dict = {1: 'a', 2: 'b'}

for k in my_dict:
    print(k)
    print(my_dict[k])

Output:

1
a
2
b
LaytonGB
  • 1,384
  • 1
  • 6
  • 20
1

Try to get all keys by keys() method then take first key which is 1 this:

dict = {1: 'a', 2: 'b'}
keys = list(dict.keys())
print(keys[0]) #1
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
1

There's not any builtin method to access key or values within a dictionary via indexes. But you can achieve your desired outcome by converting the dictionary to list of list via list comprehension.

dictt = {1: 'a', 2: 'b'}
dict_items = [[k,v] for k,v in dictt.items()]
print(dict_items)
>> [[1, 'a'], [2, 'b']]

If you want first key in the dictionary

print(dict_items[0][0])
>> 1

If you want first value in the dictionary

print(dict_items[0][1])
>> a

If you want second key in the dictionary

print(dict_items[1][0])
>> 2

If you want second value in the dictionary

print(dict_items[1][1])
>> b
Hamza usman ghani
  • 2,264
  • 5
  • 19