SujitS
SujitS

Reputation: 11423

how to get key of dictionary in python

#some dictionary data{}
data = {1:[3,1,4,2,6]}

How to print the key of data i.e

print( key_of(data) ) #print in some ways.

output:

1

What I got till now is to use data.keys() function but whenever I use that function output will be like:

dict_keys([1])

So, what is the problem with that function. Can any one suggest me the answer.?

Upvotes: 2

Views: 900

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

There's no issue with dict.keys, it returns a view like object in Python3. You can use list() on the dict to get a list of keys.

>>> data = {1:[3,1,4,2,6]}
>>> keys = list(data)
>>> keys
[1]
>>> keys[0]
1

Note: If dict contains more than one keys then the order can be arbitrary and keys[0] can return any key.

>>> dic = {'a12': 1, 'sd':'sdfd', 'sdfsd': 'sdfsd'}
>>> list(dic)               #Arbitrarily ordered
['sdfsd', 'sd', 'a12']

Upvotes: 2

Bakuriu
Bakuriu

Reputation: 101959

Simply do:

print(list(data))

to print all the keys. If you want to print a specific key then you'll have to search for it:

print(next(key for key, value in data.items() if value == something))

Note that there is no guarantee on the order of the keys.

>>> data = {'a': 1, 'aa': 2, 'b': 3, 'cd': 4}
>>> list(data)
['cd', 'a', 'b', 'aa']
>>> data['f'] = 1
>>> list(data)
['cd', 'a', 'b', 'aa', 'f']
>>> del data['a']
>>> list(data)
['cd', 'b', 'aa', 'f']
>>> data[1] = 1
>>> list(data)
['cd', 1, 'b', 'aa', 'f']
>>> for c in ('cde', 'fgh', 'ijk', 'rmn'):
...     data[c] = 1
... 
>>> list(data)
[1, 'aa', 'cde', 'cd', 'rmn', 'b', 'ijk', 'fgh', 'f']

Note how the keys do not follow alphabetical order, and how inserted keys aren't always appended to the list of keys. Also after some insertions some key were swapped. Removing/inserting keys can change the order in unpredictable ways.

Upvotes: 2

Related Questions