Access an arbitrary element in a dictionary in Python

Question:

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

mydict[mydict.keys()[0]]

Is there any better way to do this?

Asked By: Stan

||

Answers:

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.

Answered By: user319799

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.

Answered By: Alex Martelli

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()))
Answered By: Matt Joiner

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

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

Answered By: Philipp Meier

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
Answered By: swK

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]
Answered By: Xb74Dkjb

For both Python 2 and 3:

import six

six.next(six.itervalues(d))
Answered By: oblalex

In python3

list(dict.values())[0]
Answered By: Oleg Matei

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
Answered By: animaacija

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.

Answered By: maxbellec

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'
Answered By: Thomas Browne

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'
Answered By: jpp
first_key, *rest_keys = mydict
Answered By: user1994083

Another way to do this in one line while keeping the dictionary intact is:

arbitrary_value = mydict.setdefault(*mydict.popitem())

popitem() returns a tuple of (key, value) for the last item that was added into the dictionary and this pair is passed into setdefault as positional arguments. The setdefault tries to insert key into mydict with value value if it doesn’t already exist, but does nothing if does exist; and then returns the value of that key to the caller. Because we already popped the (key, value) pair out of the dictionary, we insert it back into it via setdefault and then proceed to return value, which is what we want.

Answered By: LurkerZ
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.