返回字典中的第一个键 - Python 3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45836356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:18:31  来源:igfitidea点击:

Return the first key in Dictionary - Python 3

pythonpython-3.x

提问by Mohamed Ali JAMAOUI

I'm trying to print the key and value using the below code :

我正在尝试使用以下代码打印键和值:

data = {"Key1" : "Value1", "Key2" : "Value2"}
print(data.keys()[1])   
print(data.values()[1])

I get the error

我收到错误

'dict_keys' object does not support indexing

What is wrong with the mentioned code?

上面提到的代码有什么问题?

Accepted Output :

接受的输出:

Key2
Value2

采纳答案by BoarGules

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.

它确实取决于您所说的first是什么意思。在 Python 3.6 中,字典中的条目按键排序,但可能与您期望的方式不同。

To take your example:

以你的例子为例:

>>> data = {"Key1" : "Value1", "Key2" : "Value2"}

Now add the key 0:

现在添加密钥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:

这说明了不应该依赖于排序的原则,它仅由 dict 实现定义,在 CPython 3.6 及更高版本中,它是条目的顺序。以不同的方式说明这一点:

>>> 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 forceall 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.)

我想对... dicts 的顺序表示感谢。是的,在 CPython 3.6 和 PyPy 中,它们都是有序的,但这是一个实现细节。我不想强迫所有其他实现效仿。我也不希望太多人开始依赖于此,因为他们的代码将在 3.5 中崩溃。(需要依赖关键字 args 或类属性排序的代码应该比较少见;但是人们会开始太容易依赖所有 dicts 的排序。我想提醒他们,他们正在冒险,他们的代码不会向后兼容。)

The full post is here.

完整的帖子在这里

回答by Mohamed Ali JAMAOUI

in python3 data.keys()returns a dict_keysobject, so, in general, apply list on it to be able to index/slice it:

在 python3 中data.keys()返回一个dict_keys对象,因此,通常,在其上应用列表以便能够对其进行索引/切片:

data = {"Key1" : "Value1", "Key2" : "Value2"}
print(data.keys()) 
# output >>> dict_keys(['Key1', 'Key2'])
print(list(data.keys())[1])   
# output >>> Key2
print(list(data.values())[1])
# output >>> Value2

For your specific case, you need to convert the dictionary to an ordered one to conserve the order and get the first element as follows:

对于您的特定情况,您需要将字典转换为有序字典以保存顺序并获取第一个元素,如下所示:

from collections import OrderedDict 
data = {"Key1" : "Value1", "Key2" : "Value2"}
data = OrderedDict(data)
print(data)
# output >>> OrderedDict([('Key1', 'Value1'), ('Key2', 'Value2')])
print(list(data.keys())[0])
# output >>> Key1

Edit:

编辑:

Based on comments from @Mseifert (thanks), preserving the order after conversion from the unordered dictionary to the ordered one is only an implementation detail that works in python3.6 and we cannot rely on, here's the discussion Mseifert shared:

根据@Mseifert 的评论(感谢),从无序字典转换为有序字典后保留顺序只是一个在 python3.6 中有效的实现细节,我们不能依赖,这里是 Mseifert 分享的讨论:

So the correct way to do what you want is to explicitly define the order

所以做你想做的正确方法是明确定义顺序

from collections import OrderedDict
data = OrderedDict([('Key1', 'Value1'), ('Key2', 'Value2')])
print(list(data.keys())[0])

回答by cssyphus

Shortest:

最短:

mydict = {"Key1" : "Value1", "Key2" : "Value2"}
print( next(iter(mydict)) ) # 'Key1'

For both the key and value:

对于键和值:

print( next(iter( mydict.items() )) ) # ('Key1', 'Value1')

回答by MSeifert

Dictionaries are unordered and in the newer Python versions the hashes of strings are randomized (per session). So you have to accept that what you get as "n"-th key (or value) of a dictionary isn't predictable (at least when the keys are strings).

字典是无序的,在较新的 Python 版本中,字符串的哈希是随机的(每个会话)。所以你必须接受你得到的作为字典的“n”个键(或值)是不可预测的(至少当键是字符串时)。

But if you just want the element that happens to be "first" (or "second") just use listto convert the dict_keysto an sequence that can be indexed:

但是,如果您只想要恰好是“第一个”(或“第二个”)的元素,只需使用list将 转换为dict_keys可以索引的序列:

print(list(data.keys())[1])   
print(list(data.values())[1])

However, my suggestion would be to use an OrderedDictinstead of a normal dict to make the result deterministic:

但是,我的建议是使用一个OrderedDict而不是普通的 dict 来使结果具有确定性:

from collections import OrderedDict
data = OrderedDict([("Key1", "Value1"), ("Key2", "Value2")])
print(list(data.keys())[1])     # Key2
print(list(data.values())[1])   # Value2

回答by Richard Neumann

In Python, dicts are unordered data structures. Therefore there is no firstkey. If you want to have a dict-like data structure with internal ordering of keys, have a look at OrderedDict.

在 Python 中,dicts 是无序的数据结构。因此没有第一把钥匙。如果您想拥有dict具有内部键顺序的类似数据结构,请查看OrderedDict.

回答by dtar

For Python 3 you can simply do

对于 Python 3,你可以简单地做

first_key = next(iter(data.keys()))
print(first_key)   # 'Key1'

回答by techkuz

Dicts represent an unordered datatype, therefore there is no indexing. There is an option in collections. Try OrderedDict.

字典表示无序数据类型,因此没有索引。集合中有一个选项。试试 OrderedDict。

import collections

d = collections.OrderedDict()
d['Key1'] = 'Value1'
d['Key2'] = 'Value2' # that's how to add values to OrderedDict

items = list(d.items())
print(items)
#[('Key1', 'Value1'), ('Key2', 'Value2')]
print(items[0])
#('Key1', 'Value1')
print(items[1])
#('Key2', 'Value2')