Return the first key in Dictionary - Python 3
It does rather depend on what you mean by first. In Python 3.6, entries in a dictionary are ordered by the key, but probably not quite in the way you expect.
To take your example:
>>> data = {"Key1" : "Value1", "Key2" : "Value2"}
Now add the key 0
:
>>> data[0] = "Value0"
>>> data
{'Key1': 'Value1', 'Key2': 'Value2', 0: 'Value0'}
So the zero comes at the end. But if you construct the dict from scratch, like this:
>>> data = {0: "Value0", "Key1" : "Value1", "Key2" : "Value2"}
you get this result instead
>>> data
{0: 'Value0', 'Key1': 'Value1', 'Key2': 'Value2'}
This illustrates the principle that you should not depend on the ordering, which is defined only by the dict implementation, which, in CPython 3.6 and later, is order of entry. To illustrate that point in a different way:
>>> data = {0: "Value0", "Key1" : "Value1", "Key2" : "Value2"}
>>> sorted(data.keys())
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
sorted(data.keys())
TypeError: '<' not supported between instances of 'str' and 'int'
Guido has this to say on the subject:
I'd like to handwave on the ordering of ... dicts. Yes, in
CPython 3.6 and in PyPy they are all ordered, but it's an
implementation detail. I don't want to force all other
implementations to follow suit. I also don't want too many people
start depending on this, since their code will break in 3.5. (Code
that needs to depend on the ordering of keyword args or class
attributes should be relatively uncommon; but people will start to
depend on the ordering of all dicts all too easily. I want to remind
them that they are taking a risk, and their code won't be backwards
compatible.)
The full post is here.
dict.keys()[0] on Python 3
dict.keys()
is a dictionary view. Just use list()
directly on the dictionary instead if you need a list of keys, item 0 will be the first key in the (arbitrary) dictionary order:
list(prob)[0]
or better still just use:
next(iter(dict))
Either method works in both Python 2 and 3 and the next()
option is certainly more efficient for Python 2 than using dict.keys()
. Note however that dictionaries have no set order and you will not know what key will be listed first.
It looks as if you are trying to find the maximum key instead, use max()
with dict.get
:
def Ciudad(prob):
return max(prob, key=prob.get)
The function result is certainly going to be the same for any given prob
dictionary, as your code doesn't differ in codepaths between the random number comparison branches of the if
statement.
Get value from dictionary for first key that exists
Using a plain old for loop, the flow control is clearest:
for k in 'CEB':
try:
v = d[k]
except KeyError:
pass
else:
break
else:
v = None
If you want to one-liner it, that's possible with a comprehension-like syntax:
v = next((d[k] for k in 'CEB' if k in d), None)
Return first N key:value pairs from dict
There's no such thing a the "first n" keys because a dict
doesn't remember which keys were inserted first.
You can get any n key-value pairs though:
n_items = take(n, d.iteritems())
This uses the implementation of take
from the itertools
recipes:
from itertools import islice
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
See it working online: ideone
Update for Python 3.6
n_items = take(n, d.items())
Get first value in dict from a list of keys
You can apply next()
with generator expression:
result = next(d[k] for k in labels if k in d)
Upd. Code above works but it doesn't fit 100%, because it iterates over labels
and retrieve value of first key, which not always first occurrence.
To get value of first occurrence of any key from labels
use next code:
result = next(v for k, v in d.items() if k in labels)
Python - find first dictionary key in template
What I finally done was as following:
creating an OrderedDict out of my Dictionary, making sure that it's sorted by dates Descending:
duration_dict = OrderedDict(sorted(duration_dict.items(), key=lambda t: t[0], reverse=True))
So now I can be sure that the first key is also the latest year.
and for presenting all the key,value pairs without the first year I used forloop.first, as suggested by @bozdoz:
{% for year, durations in duration_dict.items %}
{% if not forloop.first %}
<optgroup label={{ year }}>
{% endif %}
{% for duration in durations %}
<option data-from-date="{{ duration.from_date }}" data-to-date="{{ duration.to_date }}" value={{ duration.duration_id }}>{{ duration.from_date }}
- {{ duration.to_date }}</option>
{% endfor %}
{% endfor %}
How to access the first and the last elements in a dictionary?
Use an OrderedDict
, because a normal dictionary doesn't preserve the insertion order of its elements when traversing it. Here's how:
# import the right class
from collections import OrderedDict
# create and fill the dictionary
d = OrderedDict()
d['first'] = 1
d['second'] = 2
d['third'] = 3
# retrieve key/value pairs
els = list(d.items()) # explicitly convert to a list, in case it's Python 3.x
# get first inserted element
els[0]
=> ('first', 1)
# get last inserted element
els[-1]
=> ('third', 3)
Best way to get a single key from a dictionary?
Which way is best?
I recommend using next(iter(d))
over list(mydict.keys())[0]
to retrieve a key from a dictionary. As you suspected, using next(iter(d))
is much better in terms of efficiency.
The efficiency difference can be observed by timing each method:
>>> import timeit
>>> setup='from string import ascii_letters; d = {k: v for k, v in enumerate(ascii_letters)}'
>>> timeit.timeit(stmt='list(d.keys())[0]', setup=setup)
1.0895291733333334
>>> timeit.timeit(stmt='next(iter(d))', setup=setup)
0.2682935466666656
The choice of using next(iter(d))
over list(d.keys())[0]
becomes very, very obvious as the size of the dictionary increases:
>>> setup='d = {k: v for k, v in enumerate(range(500, 10000))}'
>>> timeit.timeit(stmt='list(d.keys())[0]', setup=setup)
98.52252842666667
>>> timeit.timeit(stmt='next(iter(d))', setup=setup)
0.2720192000000452
next(iter(d))
performs so much better than list(d.keys())[0]
mainly because it avoids creating a potential huge list of all of the dictionaries keys in memory, when it really only needs the first element.
Related Topics
How to Read Image Data from a Url in Python
How to Get Rid of the B-Prefix in a String in Python
Running Two Python Scripts With Bash File
Django.Db.Utils.Operationalerror: (1045, Access Denied for User '<User>'@'Localhost'
Open() Gives Filenotfounderror/Ioerror: Errno 2 No Such File or Directory
Convert Np.Array of Type Float64 to Type Uint8 Scaling Values
Interactive Matplotlib Figures in Google Colab
Python File Opens and Immediately Closes
How to Count Duplicate Rows in Pandas Dataframe
Python Read File Determined by Separator \R\N
How to Downgrade Tensorflow, Multiple Versions Possible
How to Get the Latest File in a Folder
Printing Simple Diamond Pattern in Python
How to Modify the Navigation Toolbar Easily in a Matplotlib Figure Window
Python: How to Calculate the Average Word Length in a Sentence Using the .Split Command
How to Check Whether All Elements of Array Are in Between Two Values
Importerror: No Module Named Psycopg2 After Install
Get Row Value of Maximum Count After Applying Group by in Pandas