在 Python 中,什么决定了迭代 kwargs 时的顺序?

发布于 2024-12-28 13:22:43 字数 420 浏览 1 评论 0原文

在 python 中,我编写了这个函数来教自己 **kwargs 在 Python 中如何工作:

def fxn(a1, **kwargs):
    print a1
    for k in kwargs:
        print k, " : ", kwargs[k]

然后我使用以下命令调用该函数

fxn(3, a2=2, a3=3, a4=4)

这是我的 Python 解释器打印的输出:

3
a3  :  3
a2  :  2
a4  :  4

Why did the for loop print the value a3 在 a2 之前,即使我先将 a2 输入到我的函数中?

In python, I wrote this function to teach myself how **kwargs works in Python:

def fxn(a1, **kwargs):
    print a1
    for k in kwargs:
        print k, " : ", kwargs[k]

I then called this function with

fxn(3, a2=2, a3=3, a4=4)

Here was the output that my Python interpreter printed:

3
a3  :  3
a2  :  2
a4  :  4

Why did the for loop print the value of a3 before that of a2 even though I fed a2 into my function first?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

荆棘i 2025-01-04 13:22:43

kwargs 是一本字典。字典是无序的——简单地说,顺序是未指定的,并且是实现细节。仔细观察会发现,顺序会根据项目的哈希值、插入顺序等而发生很大变化,因此您最好不要依赖与之相关的任何内容。

kwargs is a dictionary. Dictionaries are unordered - simply put, the order is unspecified and an implementation detail. Peeking under the hood will show that the order varies wildly depending on the hash values of the items, the order of insertion, etc. so you better don't rely on anything related to it.

丢了幸福的猪 2025-01-04 13:22:43

这是一本字典。并且,正如文档中提到的,字典没有顺序(来自 http ://docs.python.org/tutorial/datastructs.html#dictionaries):

最好将字典视为一组无序的键:值对,并要求键是唯一的(在一个字典内)。

但是您可以按某种顺序处理它,例如:

  • 使用sorted()

    def fxn(a1, **kwargs):
        打印a1
        for k in Sorted(kwargs): # 注意“kwargs”被“sorted(kwargs)”替换
            打印 k, " : ", kwargs[k]
    
  • 或使用OrderedDict类型(您可以将OrderedDict对象作为参数传递包含所有键值对):

    从集合导入 OrderedDict
    
    def fxn(a1, ordkwargs):
        打印a1
        对于 ordkwargs 中的 k:
            打印 k, " : ", ordkwargs[k]
    
    fxn(3, OrderedDict((('a2',2), ('a3',3), ('a4',4))))
    

This is a dictionary. And, as mentioned in documentation, dictionary has no order (from http://docs.python.org/tutorial/datastructures.html#dictionaries):

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

But you can make it processed in some order, like that:

  • using sorted():

    def fxn(a1, **kwargs):
        print a1
        for k in sorted(kwargs): # notice "kwargs" replaced by "sorted(kwargs)"
            print k, " : ", kwargs[k]
    
  • or by using OrderedDict type (you can pass OrderedDict object as parameter containing all the key-value pairs):

    from collections import OrderedDict
    
    def fxn(a1, ordkwargs):
        print a1
        for k in ordkwargs:
            print k, " : ", ordkwargs[k]
    
    fxn(3, OrderedDict((('a2',2), ('a3',3), ('a4',4))))
    
晨曦÷微暖 2025-01-04 13:22:43

这最终在 3.6 版本中引入:dict 现在已排序,因此保留了关键字参数顺序。

Python 3.6.0 (default, Jan 13 2017, 13:27:48) 
>>> def print_args(**kwargs):
...     print(kwargs.keys())
... 
>>> print_args(first=1, second=2, third=3)
dict_keys(['first', 'second', 'third'])

This has finally been introduced in the 3.6 release: dicts are now ordered, therefore the keyword argument order is preserved.

Python 3.6.0 (default, Jan 13 2017, 13:27:48) 
>>> def print_args(**kwargs):
...     print(kwargs.keys())
... 
>>> print_args(first=1, second=2, third=3)
dict_keys(['first', 'second', 'third'])
拿命拼未来 2025-01-04 13:22:43

不幸的讽刺是 **kwargs 的字典化意味着以下内容将不起作用(至少不是人们期望的方式):

od = OrderedDict(a=1, b=2, c=3)

由于关键字参数首先构建到无序字典中,因此您不能依赖它们将按照列出的顺序插入到 OrderedDict 中。 :(

The unfortunate irony is that the dict-ification of **kwargs means that the following will not work (at least not the way one would expect):

od = OrderedDict(a=1, b=2, c=3)

Since the keyworded args are first built into an unordered dict, you cannot depend that they will be inserted into the OrderedDict in the order they are listed. :(

千鲤 2025-01-04 13:22:43

由于 kwargs 是一个 Python 字典,它是作为 哈希表,它的顺序不被保留并且实际上是随机的。

实际上,作为对许多编程语言中最近的安全问题的修复,将来的顺序甚至可能是程序调用之间的更改(Python 解释器的调用)。

Since kwargs is a Python dictionary, which is implemented as a hash table, its ordering is not preserved and is effectively random.

Actually, as a fix to a recent security issue in many programming languages, in the future the order may even change between invocations of your program (invocations of the Python interpreter).

满天都是小星星 2025-01-04 13:22:43

kwargs 是一个字典,在 Python 中它们没有排序,因此结果本质上是(伪)随机的。

kwargs is a dictionary, in Python these are not ordered so the result is essentially (pseudo-) random.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文