Reputation: 3058
I have the following list
:
is_censored = [[True, True], [False, True], [False, False]]
which I want to place into a dictionary
with keys/values equal to is_censored_1 = [True, True]
, is_censored_2=[False, True]
and is_censored_3=[False, False]
.
Can this be achieved pythonically?
So far I have this:
data = dict()
for i, value in enumerate(is_censored):
data['_'.join(['is_censored', str(i + 1)])] = value
which yields the right result:
data = {'is_censored_1': [True, True], 'is_censored_2': [False, True], 'is_censored_3': [False, False]}
but is not that appealing to the eyes.
Upvotes: 1
Views: 1046
Reputation: 88226
You can use a dictionary comprehension with enumerate
to format the f-strings:
{f'is_censored_{i+1}': l for i,l in enumerate(is_censored)}
{'is_censored_1': [True, True],
'is_censored_2': [False, True],
'is_censored_3': [False, False]}
Note: for python versions < 3.6
use string.format()
as in @devesh's answer. You can check the docs for more details
Upvotes: 7
Reputation: 11228
is_censored = [[True, True], [False, True], [False, False]]
res ={'is_censored_{}'.format(i+1):is_censored[i] for i in range(len(is_censored))}
output
{'is_censored_1': [True, True],
'is_censored_2': [False, True],
'is_censored_3': [False, False]}
Upvotes: 1
Reputation: 20490
You can use dictionary comprehension for this, where you get both index and item of list is_censored
using enumerate
, then make key-value pairs accordingly!
is_censored = [[True, True], [False, True], [False, False]]
res = {'is_censored_{}'.format(idx+1):item for idx, item in enumerate(is_censored)}
print(res)
The output will be
{'is_censored_1': [True, True], 'is_censored_2': [False, True], 'is_censored_3': [False, False]}
Upvotes: 3