繁体   English   中英

Python-如何在字典中使用try / except语句

[英]Python - How to use try/except statement in dictionary

我试图这样做,但是没有用。 只是为了澄清一下,我希望值等于list [0](如果存在)。 谢谢。

    dictionary = {
    try:
        value : list[0],
    except IndexError:
        value = None
    }

您必须将try..exept放在该try..exept 周围 您不能像以前那样将其放入表达式中:

try:
    dictionary = {value: list[0]}
except IndexError:
    dictionary = {value: None}

或者,将分配移到另一套语句中:

dictionary = {value: None}
try:
    dictionary[value] = list[0]
except IndexError:
    pass

或显式测试list的长度,因此您可以选择带条件表达式的None

dictionary = {
    value: list[0] if list else None,
}

如果列表对象不为空,则if list测试为true。

您还可以使用itertools.izip_longest()函数 (在Python 3中为itertools.zip_longest() )来配对键和值。 它将以最短的顺序整齐地切断,并为缺少的元素填写None值:

from itertools import izip_longest
dictionary = dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))

在这里,如果list_of_values没有3个值,则它们的匹配键会自动设置为None

>>> from itertools import izip_longest
>>> list_of_values = []
>>> dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
{'key3': None, 'key2': None, 'key1': None}
>>> list_of_values = ['foo']
>>> dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
{'key3': None, 'key2': None, 'key1': 'foo'}
>>> list_of_values = ['foo', 'bar']
>>> dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
{'key3': None, 'key2': 'bar', 'key1': 'foo'}
>>> list_of_values = ['foo', 'bar', 'baz']
>>> dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
{'key3': 'baz', 'key2': 'bar', 'key1': 'foo'}

您实际上可以使用'in'关键字查看字典中是否存在某些内容作为键

if list[0] in dictionary:
    value = list[0]
else:
    value = None

请注意,请避免将“列表”用作变量名。

我假设您正在尝试做的是:

new_dictionary = dict()
if list[0] in dictionary:
    new_dictionary['value'] = list[0]
else:
    new_dictioanry['value'] = None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM