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.
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.items())
This uses the implementation of take
from the itertools
recipes:
from itertools import islice
def take(n, iterable):
"""Return the first n items of the iterable as a list."""
return list(islice(iterable, n))
See it working online: ideone
For Python < 3.6
n_items = take(n, d.iteritems())
How can I get the name of the first key in a dictionary?
You can use task.Result.Error.ErrorDetails.Keys.First()
.
Alternativly you may also query the first KeyValuePair
from your dirctionary:
var kv = task.Result.Error.ErrorDetails.First();
var KeyName = kv.Key;
However you should not rely on the order of the keys, because Dictionary<T, S>
does not have any guranateed order. If you really need a determinstic order of elements in a key-value-based map, you may use a SortedDictionary
instead.
How to get the name of a key without knowing the name of the key
You can convert the dictionary keys and/or values to a list [please note powerpoint_levels is used as defined in the code provided]
keys = list(powerpoint_levels.keys())
values = list(powerpoint_levels.values())
print(keys[0]) #first key
print(values[0]) #first value
To get the second key or second value, just switch the 0's for 1's.
Get first key from Dictionarystring, string
Assuming you're using .NET 3.5:
dic.Keys.First();
Note that there's no guaranteed order in which key/value pairs will be iterated over in a dictionary. You may well find that in lots of cases you get out the first key that you put into the dictionaries - but you absolutely must not rely on that. As Skirwan says, there isn't really a notion of "first". Essentially the above will give you "a key from the dictionary" - that's about all that's guaranteed.
(If you don't know whether the dictionary is empty or not, you could use FirstOrDefault
.)
How to get the first value in a Python dictionary
Try this way:
my_list = [elem[0] for elem in your_dict.values()]
Offtop:
I think you shouldn't use camelcase, it isn't python way
UPD:
inspectorG4dget notes, that result won't be same. It's right. You should use collections.OrderedDict to implement this correctly.
from collections import OrderedDict
my_dict = OrderedDict({'BigMeadow2_U4': (1609.32, 22076.38, 3.98), 'MooseRun': (57813.48, 750187.72, 231.25), 'Hwy14_2': (991.31, 21536.80, 6.47) })
Access an arbitrary element in a dictionary in Python
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.
Related Topics
Python/Selenium Incognito/Private Mode
Why Is Pip Installing an Old Version of My Package
Serving Dynamically Generated Zip Archives in Django
Efficiently Updating Database Using SQLalchemy Orm
How to Install the Yaml Package for Python
Cleanest Way to Hide Every Nth Tick Label in Matplotlib Colorbar
Python: Fastest Way to Create a List of N Lists
About the Pil Error -- Ioerror: Decoder Zip Not Available
Python Parse Comma-Separated Number into Int
How to Write Code to Autocomplete Words and Sentences
Beautiful Soup 4 Find_All Don't Find Links That Beautiful Soup 3 Finds
Python Create Unix Timestamp Five Minutes in the Future
How to Find Which Columns Contain Any Nan Value in Pandas Dataframe
Bin Size in Matplotlib (Histogram)
Add Zeros to a Float After the Decimal Point in Python