Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字典语法,具有for条件_Python_Dictionary_Dictionary Comprehension_Iterable Unpacking - Fatal编程技术网

Python字典语法,具有for条件

Python字典语法,具有for条件,python,dictionary,dictionary-comprehension,iterable-unpacking,Python,Dictionary,Dictionary Comprehension,Iterable Unpacking,我有这本字典 states = { 'CT': 'Connecticut', 'CA': 'California', 'NY': 'New York', 'NJ': 'New Jersey' } 代码在这里 state2 = {state: abbrev for abbrev, state in states.items()} 我正在试图了解abbrev for abbrev的工作原理。我也不清楚状态:到底是什么。我得到了第二部分(states.ite

我有这本字典

states = {
    'CT': 'Connecticut',
    'CA': 'California',
    'NY': 'New York',
    'NJ': 'New Jersey'
    }
代码在这里

state2 = {state: abbrev for abbrev, state in states.items()}
我正在试图了解abbrev for abbrev的工作原理。我也不清楚
状态:
到底是什么。我得到了第二部分(states.items()中的状态)。这项研究的结果是

{'Connecticut': 'CT', 'California': 'CA', 'New York': 'NY', 'New Jersey': 'NJ'}

但我不确定这是怎么回事。。提前谢谢你。

这里发生的事情被称为字典理解,一旦你看够了,阅读起来就很容易了

state2 = {state: abbrev for abbrev, state in states.items()}
如果您查看一下
state:abbrev
,可以立即看出这是一种常规的对象分配语法。您正在将abbrev的值分配给状态键。但什么是国家,以及阿巴雷夫

您只需查看下一条语句,
for abbrev,state in states.items()

这里有一个for循环,其中abbrev是键,state是项,因为states.items()返回一个键和值对


因此,字典理解似乎是在为我们创建一个对象,通过循环对象并在循环过程中指定键和值。

字典理解类似于列表理解
states.items()
是一个生成器,它将返回原始字典中每个项的键和值。因此,如果您要声明一个空字典,遍历项目,然后翻转键和值,那么您将拥有一个新的字典,它是原始字典的翻转版本

state2 = {}
for abbrev, state in states.items():
    state2[state] = abbrev
从循环结构转换

翻转行的顺序

state2 = {}
    state2[state] = abbrev
for abbrev, state in states.items():
state2 = {state: abbrev for abbrev, state in states.items()}
延伸支架以包围一切

state2 = {
    state2[state] = abbrev
for abbrev, state in states.items():
}
修复分配,因为未分配
state2

state2 = {
    state: abbrev
for abbrev, state in states.items():
}
删除原始的

state2 = {
    state: abbrev
for abbrev, state in states.items()
}
把线整理好

state2 = {}
    state2[state] = abbrev
for abbrev, state in states.items():
state2 = {state: abbrev for abbrev, state in states.items()}

使用sytax通常更快,更受欢迎。

这是否回答了您的问题?对于添加的少量上下文,这与dict(map(reversed,states.items())相同,并与