Accessing any element in a dictionary in Python

Posted by tomerg3 on Fri, 24 Jan 2020 02:26:09 +0100

If mydict is not empty, I will access any element as follows:

mydict[mydict.keys()[0]]

Is there any better way?

#1st floor

If you only need to access one element (since dictionaries do not guarantee sorting, they are the first occasional element), you only need to Python 2 Do this:

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

Note (to my knowledge) that Python does not guarantee that two consecutive calls to either of these methods will return a list in the same order.This functionality is not supported in Python 3.

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

#2nd floor

In python3, the way:

dict.keys() 

Returns a value of type dict_keys(), in which case we get an error when we get the first member of the dict's key:

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

Finally, I converted dict.keys() to list @ 1st and got the first member by splicing the list:

list(dict.keys())[0]

#3rd floor

For Python 2 and 3:

import six

six.next(six.itervalues(d))

#4th floor

On Python 3, nondestructive and iterative:

next(iter(mydict.values()))

On Python 2, nondestructive and iterative:

mydict.itervalues().next()

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

six.next(six.itervalues(mydict))

Although it's still mysterious at this point, I still like your code better.

If you want to delete any items, do the following:

key, value = mydict.popitem()

Note that "first" is not an appropriate term here.This is an "any" item because dict is not of an ordered type.

#5th floor

As others have mentioned, there is no First Item because dictionaries have no guaranteed order (they are implemented as hash tables).For example, if you want a value corresponding to the minimum key, the Dict [min (thedict)] will do this.If you care about the order in which keys are inserted, that is, first refers to the earliest insertion, in Python 3.1 you can use collections.OrderedDict For older versions of Python, download, install, and use ordered dict reverse migration (version 2.4 and later), which you can use in here Find it.

Python 3.7 Now? Dictionaries are sorted in insertion order.

#6th floor

Ignoring the issue of dictionary sorting might be better:

next(dict.itervalues())

In this way, we avoid item lookups and generate lists of keys that we don't use.

Python3

next(iter(dict.values()))

#7th floor

In python3

list(dict.values())[0]

#8th floor

How's this?Not mentioned here yet.

py 2&3

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

#9th floor

Get the key

next(iter(mydict))

Get value

next(iter(mydict.values()))

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 inert in Python 3, but not in Python 2.

#10th floor

You can do this at any time:

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

If sorting makes any sense to you, it will give you a consistent sort key (about built-in.hash(), I guess).For example, this means that numeric types will be 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 dictionaries are sorted when printed.But the keyset is essentially a hash map!

#11th floor

There are no external libraries to run on Python 2.7 and 3.x:

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

For the aribtrary key, simply ignore.values ()

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

#12th floor

dict subclassification is a method, albeit inefficient.If you provide 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'

13th floor

The simplest method for python3:

list(dict.keys())[0]

#14th floor

first_key, *rest_keys = mydict

#15th floor

Update @swK's answer based on @alldayremix's comments:

Used 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
Published 0 original articles, won approval 2, visited 5833
Private letter follow

Topics: Python