问题:在Python中访问字典中的任意元素
如果a mydict
不为空,则访问以下任意元素:
mydict[mydict.keys()[0]]
有什么更好的方法吗?
If a mydict
is not empty, I access an arbitrary element as:
mydict[mydict.keys()[0]]
Is there any better way to do this?
回答 0
在Python 3上,非破坏性和迭代性地:
next(iter(mydict.values()))
在Python 2上,非破坏性和迭代性地:
mydict.itervalues().next()
如果希望它在Python 2和3中都可以使用,则可以使用该six
包:
six.next(six.itervalues(mydict))
尽管在这一点上它还是很神秘的,但我还是更喜欢您的代码。
如果要删除任何项目,请执行以下操作:
key, value = mydict.popitem()
请注意,“ first”在此处可能不是合适的术语,因为dict
在Python <3.6中不是有序类型。Python 3.6+ dicts
已订购。
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.
回答 1
如果您只需要访问一个元素(由于字典不能保证排序,则是偶然的第一个元素),您可以在Python 2中简单地做到这一点:
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
请注意(据我所知),Python不保证对这些方法中任何一个的2个连续调用将返回具有相同顺序的list。Python3不支持此功能。
在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
If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in Python 2:
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
Please note that (at best of my knowledge) Python does not guarantee that 2 successive calls to any of these methods will return list with the same ordering. This is not supported with Python3.
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
回答 2
在python3中,方式:
dict.keys()
返回类型为dict_keys()的值,当通过这种方式获得dict的键的第一个成员时,我们将得到一个错误:
dict.keys()[0]
TypeError: 'dict_keys' object does not support indexing
最后,我将dict.keys()转换为列表@ 1st,并通过列表拼接方法获得了第一个成员:
list(dict.keys())[0]
In python3, The way :
dict.keys()
return a value in type : dict_keys(), we’ll got an error when got 1st member of keys of dict by this way:
dict.keys()[0]
TypeError: 'dict_keys' object does not support indexing
Finally, I convert dict.keys() to list @1st, and got 1st member by list splice method:
list(dict.keys())[0]
回答 3
拿到钥匙
next(iter(mydict))
获得价值
next(iter(mydict.values()))
两者兼得
next(iter(mydict.items())) # or next(iter(mydict.viewitems())) in python 2
前两个是Python 2和3。后两个在Python 3中是惰性的,但在Python 2中则不是。
to get a key
next(iter(mydict))
to get a value
next(iter(mydict.values()))
to get 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 lazy in Python 3, but not in Python 2.
回答 4
正如其他人提到的那样,由于字典没有保证的顺序(它们被实现为哈希表),因此没有“第一项”。例如,如果您想要与最小键对应的值,则thedict[min(thedict)]
可以这样做。如果您关心键的插入顺序,即“首先”是指“最早插入”,那么在Python 3.1中,您可以使用collections.OrderedDict,即将在即将发布的Python 2.7中使用;对于旧版本的Python,请下载,安装并使用有序的dict反向移植(2.4及更高版本),您可以在此处找到。
Python 3.7
现在,字典按插入顺序排序。
As others mentioned, there is no “first item”, since dictionaries have no guaranteed order (they’re implemented as hash tables). If you want, for example, the value corresponding to the smallest key, thedict[min(thedict)]
will do that. If you care about the order in which the keys were inserted, i.e., by “first” you mean “inserted earliest”, then in Python 3.1 you can use collections.OrderedDict, which is also in the forthcoming Python 2.7; for older versions of Python, download, install, and use the ordered dict backport (2.4 and later) which you can find here.
Python 3.7
Now dicts are insertion ordered.
回答 5
这个怎么样。这里还没有提到。
py 2&3
a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2
How about, this. Not mentioned here yet.
py 2 & 3
a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2
回答 6
忽略有关字典排序的问题,这可能会更好:
next(dict.itervalues())
这样,我们避免了项目查找,并生成了我们不使用的键列表。
Python3
next(iter(dict.values()))
Ignoring issues surrounding dict ordering, this might be better:
next(dict.itervalues())
This way we avoid item lookup and generating a list of keys that we don’t use.
Python3
next(iter(dict.values()))
回答 7
在python3中
list(dict.values())[0]
In python3
list(dict.values())[0]
回答 8
您可以随时这样做:
for k in sorted(d.keys()):
print d[k]
如果排序对您有任何意义,这将为您提供一致的排序键(关于内置 .hash()我猜)。例如,这意味着即使您扩展字典,数字类型也会一致地排序。
例
# 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())
请注意,字典在打印时已排序。但是键集本质上是一个哈希图!
You can always do:
for k in sorted(d.keys()):
print d[k]
This will give you a consistently sorted (with respect to builtin.hash() I guess) set of keys you can process on if the sorting has any meaning to you. That means for example numeric types are 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 the dictionary is sorted when printed. But the key set is essentially a hashmap!
回答 9
对于Python 2和3:
import six
six.next(six.itervalues(d))
For both Python 2 and 3:
import six
six.next(six.itervalues(d))
回答 10
first_key, *rest_keys = mydict
first_key, *rest_keys = mydict
回答 11
没有外部库,可在Python 2.7和3.x上运行:
>>> list(set({"a":1, "b": 2}.values()))[0]
1
对于aribtrary键,只需忽略.values()
>>> list(set({"a":1, "b": 2}))[0]
'a'
No external libraries, works on both Python 2.7 and 3.x:
>>> list(set({"a":1, "b": 2}.values()))[0]
1
For aribtrary key just leave out .values()
>>> list(set({"a":1, "b": 2}))[0]
'a'
回答 12
子类化dict
是一种方法,尽管效率不高。如果您提供整数,它将返回d[list(d)[n]]
,否则按预期方式访问字典:
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'
Subclassing dict
is one method, though not efficient. Here if you supply 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'