Reputation: 5366
I was trying to do this, but It didn't work. Just to clarify I want value to equal list[0] if it exists. Thanks.
dictionary = {
try:
value : list[0],
except IndexError:
value = None
}
Upvotes: 0
Views: 2407
Reputation: 1121834
You'd have to put the try..exept
around the assigment; you cannot put it inside an expression like you did:
try:
dictionary = {value: list[0]}
except IndexError:
dictionary = {value: None}
Alternatively, move the assignment to a separate set of statements:
dictionary = {value: None}
try:
dictionary[value] = list[0]
except IndexError:
pass
or explicitly test for the length of list
so you can just select None
with a conditional expression:
dictionary = {
value: list[0] if list else None,
}
where the if list
test is true if the list object is not empty.
You could also use the itertools.izip_longest()
function (itertools.zip_longest()
in Python 3) to pair up keys and values; it'll neatly cut off at the shortest sequence, and fill in None
values for the missing elements:
from itertools import izip_longest
dictionary = dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
Here, if list_of_values
does not have 3 values, then their matching keys are set to None
automatically:
>>> 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'}
Upvotes: 6
Reputation: 690
You can actually use the 'in' keyword to see if something exists as a key in a dictionary
if list[0] in dictionary:
value = list[0]
else:
value = None
Just a note, avoid using 'list' as a variable name.
Here's what you're trying to do I'm assuming:
new_dictionary = dict()
if list[0] in dictionary:
new_dictionary['value'] = list[0]
else:
new_dictioanry['value'] = None
Upvotes: 0