在 Python 中,什么决定了遍历 kwargs 时的顺序? [英] In Python, what determines the order while iterating through kwargs?

查看:57
本文介绍了在 Python 中,什么决定了遍历 kwargs 时的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中,我编写了这个函数来自学 **kwargs 在 Python 中的工作原理:

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]

然后我用

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

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

Here was the output that my Python interpreter printed:

3
a3  :  3
a2  :  2
a4  :  4

为什么即使我先将 a2 输入到我的函数中,for 循环也会在 a2 之前打印 a3 的值?

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

推荐答案

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.

这篇关于在 Python 中,什么决定了遍历 kwargs 时的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆