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

Pic*_*Man 0 python dictionary try-catch

我试图这样做,但它没有用.只是为了澄清我希望值等于列表[0]如果它存在.谢谢.

    dictionary = {
    try:
        value : list[0],
    except IndexError:
        value = None
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

你必须把try..exept 周围的分配新建分配FY; 你不能把它放在像你这样的表达式中:

try:
    dictionary = {value: list[0]}
except IndexError:
    dictionary = {value: None}
Run Code Online (Sandbox Code Playgroud)

或者,将分配移动到一组单独的语句:

dictionary = {value: None}
try:
    dictionary[value] = list[0]
except IndexError:
    pass
Run Code Online (Sandbox Code Playgroud)

或者显式测试长度,list这样你就可以选择None条件表达式:

dictionary = {
    value: list[0] if list else None,
}
Run Code Online (Sandbox Code Playgroud)

if list如果列表对象不为空,则测试为真.

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

from itertools import izip_longest
dictionary = dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
Run Code Online (Sandbox Code Playgroud)

这里,如果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'}
Run Code Online (Sandbox Code Playgroud)