Access an arbitrary element in a dictionary in Python

The Question :

530 people think this question is useful

If a mydict is not empty, I access an arbitrary element as:


Is there any better way to do this?

The Question Comments :
  • What he said.. this is only really a valid question if there’s only one element in the dict, or you don’t care which you get back.
  • Yup, I just need to access to whatever element in the dict, so that’s why I want to access to first element.
  • @Stan: but as Greg said, there is no definite “first” element in dict. so maybe you should change your question, just to be clear
  • I think it is a valid question. If you need to access an arbitrary element, and you are sure that the dict is not empty, it may be a good idea to ask for the “first”, because the number of items may not be known.
  • @MichaelScheper You have to cast to list : list(mydict.keys())[0].

The Answer 1

623 people think this answer is useful

On Python 3, non-destructively and iteratively:


On Python 2, non-destructively and iteratively:


If you want it to work in both Python 2 and 3, you can use the six package:

though at this point it is quite cryptic and I’d rather prefer your code.

If you want to remove any item, do:

key, value = mydict.popitem()

Note that “first” may not be an appropriate term here because dict is not an ordered type in Python < 3.6. Python 3.6+ dicts are ordered.

The Answer 2

151 people think this answer is useful

If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in Python 2:

my_dict.keys()[0]     -> key of "first" element
my_dict.values()[0]   -> value of "first" element
my_dict.items()[0]    -> (key, value) tuple of "first" element

Please note that (at best of my knowledge) Python does not guarantee that 2 successive calls to any of these methods will return list with the same ordering. This is not supported with Python3.

in Python 3:

list(my_dict.keys())[0]     -> key of "first" element
list(my_dict.values())[0]   -> value of "first" element
list(my_dict.items())[0]    -> (key, value) tuple of "first" element

The Answer 3

58 people think this answer is useful

In python3, The way :


return a value in type : dict_keys(), we’ll got an error when got 1st member of keys of dict by this way:

TypeError: 'dict_keys' object does not support indexing

Finally, I convert dict.keys() to list @1st, and got 1st member by list splice method:


The Answer 4

26 people think this answer is useful

to get a key


to get a value


to get both

next(iter(mydict.items())) # or next(iter(mydict.viewitems())) in python 2

The first two are Python 2 and 3. The last two are lazy in Python 3, but not in Python 2.

The Answer 5

16 people think this answer is useful

As others mentioned, there is no “first item”, since dictionaries have no guaranteed order (they’re implemented as hash tables). If you want, for example, the value corresponding to the smallest key, thedict[min(thedict)] will do that. If you care about the order in which the keys were inserted, i.e., by “first” you mean “inserted earliest”, then in Python 3.1 you can use collections.OrderedDict, which is also in the forthcoming Python 2.7; for older versions of Python, download, install, and use the ordered dict backport (2.4 and later) which you can find here.

Python 3.7 Now dicts are insertion ordered.

The Answer 6

11 people think this answer is useful

How about, this. Not mentioned here yet.

py 2 & 3

a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2

The Answer 7

11 people think this answer is useful

Ignoring issues surrounding dict ordering, this might be better:


This way we avoid item lookup and generating a list of keys that we don’t use.



The Answer 8

6 people think this answer is useful

In python3


The Answer 9

2 people think this answer is useful

You can always do:

for k in sorted(d.keys()):
    print d[k]

This will give you a consistently sorted (with respect to builtin.hash() I guess) set of keys you can process on if the sorting has any meaning to you. That means for example numeric types are sorted consistently even if you expand the dictionary.


# lets create a simple dictionary
d = {1:1, 2:2, 3:3, 4:4, 10:10, 100:100}
print d.keys()
print sorted(d.keys())

# add some other stuff
d['peter'] = 'peter'
d['parker'] = 'parker'
print d.keys()
print sorted(d.keys())

# some more stuff, numeric of different type, this will "mess up" the keys set order
d[0.001] = 0.001
d[3.14] = 'pie'
d[2.71] = 'apple pie'
print d.keys()
print sorted(d.keys())

Note that the dictionary is sorted when printed. But the key set is essentially a hashmap!

The Answer 10

2 people think this answer is useful

For both Python 2 and 3:

import six

The Answer 11

1 people think this answer is useful
first_key, *rest_keys = mydict

The Answer 12

-1 people think this answer is useful

No external libraries, works on both Python 2.7 and 3.x:

>>> list(set({"a":1, "b": 2}.values()))[0]

For aribtrary key just leave out .values()

>>> list(set({"a":1, "b": 2}))[0]

The Answer 13

-2 people think this answer is useful

Subclassing dict is one method, though not efficient. Here if you supply an integer it will return d[list(d)[n]], otherwise access the dictionary as expected:

class mydict(dict):
    def __getitem__(self, value):
        if isinstance(value, int):
            return self.get(list(self)[value])
            return self.get(value)

d = mydict({'a': 'hello', 'b': 'this', 'c': 'is', 'd': 'a',
            'e': 'test', 'f': 'dictionary', 'g': 'testing'})

d[0]    # 'hello'
d[1]    # 'this'
d['c']  # 'is'

Add a Comment