python SyntaxError与dict(1 = ...),但{1:...}的作品 [英] python SyntaxError with dict(1=...), but {1:...} works

查看:169
本文介绍了python SyntaxError与dict(1 = ...),但{1:...}的作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python似乎在使用什么类型的密钥来对dicts进行接受是不一致的。或者,换句话说,它允许某种类型的键以一种方式定义dict,但不允许在其他方式:

 > >> d = {1:one,2:2} 
>>>> d [1]
'one'
>>> e = dict(1 =one,2 = 2)
文件< stdin>,第1行
SyntaxError:关键字不能是表达式

{...} 符号更根本, dict(...)只是语法糖?是不是因为Python没有办法解决这个问题(1 =one)?



'好奇...

解决方案

这不是一个 dict ,但Python语法的工件:关键字参数必须是有效的标识符,而 1 2 不是。 p>

当您希望使用Python标识符规则作为关键字之后不是字符串的任何内容时,请使用 {} 语法。在某些特殊情况下,构造函数关键字参数语法就是方便。


Python seems to have an inconsistency in what kind of keys it will accept for dicts. Or, put another way, it allows certain kinds of keys in one way of defining dicts, but not in others:

>>> d = {1:"one",2:2}
>>> d[1]
'one'
>>> e = dict(1="one",2=2)
  File "<stdin>", line 1
  SyntaxError: keyword can't be an expression

Is the {...} notation more fundamental, and dict(...) just syntactic sugar? Is it because there is simply no way for Python to parse dict(1="one")?

I'm curious...

解决方案

This is not a dict issue, but an artifact of Python syntax: keyword arguments must be valid identifiers, and 1 and 2 are not.

When you want to use anything that is not a string following Python identifier rules as a key, use the {} syntax. The constructor keyword argument syntax is just there for convenience in some special cases.

这篇关于python SyntaxError与dict(1 = ...),但{1:...}的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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