简体   繁体   中英

How to split a list of lists into dictionary key/values pairs?

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.

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

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]}
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]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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