Python 字典 : why and when I have to use sometimes ":" and sometimes "=" between the key and the value?

标签 python python-3.x dictionary

我正在研究 Python 中字典的使用,我对必须用来将键与值分开的符号以及键的“”感到越来越困惑。

通常,我会这样写:

user = {"name": "John", "surname": "Doe", "age": 34, "gender": "Male"}

但是,为什么我要写:

user = dict(name="Jack")

...在键(不写“”)和值之间有一个“=”?我还有一个例子:

def favourite_colour (**args):

    for name, colour in args.items():

        print (f"{person}'s favourite colour is {colour}.")
favourite_colour(Jude="green", Giulio="orange", Chiara="black")

请问有逻辑解释吗?

最佳答案

前者是字典,后者是函数的关键字参数。我看不出它们有何不同。

这就像问为什么 float 除法要用/,整数除法要用//。您要求 Python 做两件不同的事情,因此您需要两种不同的语法。

请注意,您也可以将 foo(bar=baz) 调用为 foo(**{bar: baz}),它提供字典作为一组关键字foo 的参数。


另请注意,: 在函数签名中已经具有意义——它是一个函数注释。

def foo(bar: "this is a bar object"):
    return raise_the(bar)

您可以将字典语法作为 {key=value, key2=value2} 的参数,但是 = 运算符意味着赋值,而您并不是真正在赋值键的值,您只是将它关联到此映射中的键。我觉得不合适。

关于Python 字典 : why and when I have to use sometimes ":" and sometimes "=" between the key and the value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51505468/

相关文章:

python - 类型错误 : fit_transform() missing 1 required positional argument: 'X'

python - 'map' 类型的对象在 Python 3 中没有 len()

一个游戏的英文单词列表

php - JavaScript 对象对关联数组(又名 map )有效吗?有哪些选择?

swift - 如何将字典的值绑定(bind)到 SwiftUI 控件?

python - 数据帧的丢弃百分比 [pandas]

python - 如何从 SQLAlchemy 中的现有表中获取列名和类型?

python - 如何在python中匹配$(....)中的字符串

android - KIVY - Python 在按下按钮时继续执行

arrays - 如何复制字节数组