简体   繁体   中英

converting a list to a dict with the last element in the list will be the value and the rest will be the key

I have a list of items, for example:

items = ['BANANA', 'FRIES', 12]

I want items[-1] to be the value of a dict and the rest will be the key like:

dict = {'BANANA FRIES': 12}

I want a piece of code that does it for any list of any length so that the last element is the value and the rest will be the key. Thank you.

{' '.join(items[:-1]): items[-1]} 

Try this one. It will work for any length of list :

items = ['BANANA', 'FRIES', 12]
di = {}
di[' '.join([item for item in items[:-1]])] = items[-1]
print(di)

The shortest way to do this:

my_list = ['BANANA', 'FRIES', 12]
my_dict = { ' '.join(my_list[:-1]) : my_list[-1] }

Doing this task with a function:

def convertToDict(my_list):
    return { ' '.join(my_list[:-1]) : my_list[-1] }

items = ['BANANA', 'FRIES', 12]
items_dict = convertToDict(items)
print(items_dict)

Result: { 'BANANA FRIES': 12 }

This should do the trick:

{" ".join(items[:-1]): items[-1]}

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