# 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:

mydict[mydict.keys()[0]]



Is there any better way to do this?

• 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].

623 people think this answer is useful

On Python 3, non-destructively and iteratively:

next(iter(mydict.values()))



On Python 2, non-destructively and iteratively:

mydict.itervalues().next()



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

six.next(six.itervalues(mydict))



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.

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



58 people think this answer is useful

In python3, The way :

dict.keys()



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

dict.keys()[0]
TypeError: 'dict_keys' object does not support indexing



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

list(dict.keys())[0]



26 people think this answer is useful

### to get a key

next(iter(mydict))



### to get a value

next(iter(mydict.values()))



### 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.

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.

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



11 people think this answer is useful

Ignoring issues surrounding dict ordering, this might be better:

next(dict.itervalues())



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

## Python3

next(iter(dict.values()))



6 people think this answer is useful

In python3

list(dict.values())[0]



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.

EXAMPLE

# 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())

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!

2 people think this answer is useful

For both Python 2 and 3:

import six

six.next(six.itervalues(d))



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



-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]
1



For aribtrary key just leave out .values()

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



-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])
else:
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'