简体   繁体   中英

Retrieve first key-value pair from a dictionary in Python without using list, iter

In case I have a huge dictionary my_dict with a complex structure.

my_dict = {'complex_key': ('complex', 'values')}

If I want to see its first key-value pair (to understand whats inside), currently I use:

list(my_dict.items())[0]

However, this dublicates all the keys in the memory. It is also inconvienient, because pdb.set_trace() does not execute expressions starting with list . It is possible to use iterator:

next(iter(my_dict.items()))

However, its inconvenient, because I cannot access n'th element easily.

Is there any other easy way to access key-value pairs of dict_items() ?

In Python 2.7 this expression used to work:

my_dict.items()[0]

Update Ended up using:

tuple(my_dict.items())[0]

This approach at least overcomes the pdb.set_trace() limitation. It also allows to easily access n'th element and does not require any imports like from itertools import islice .

The reason my_dict.items()[0] worked in Python 2.7 and not in Python 3 is because in Python 2 it returned a list and in Python 3 it returns a dictionary view .

To get the same behavior, you have to wrap it in list() or tuple() .

The most memory efficient way would be to create a tuple of the keys.

keys = tuple(my_dict.keys())
my_dict[keys[0]]

However, whenever you change the dictionary, you'd have to update/recreate keys .

Another thing to note is order is not guaranteed before Python 3.7, though once keys is created, it's order is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM