简体   繁体   English

将列表转换为字典,列表中的最后一个元素将是值,rest 将是键

[英]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:我希望 items[-1] 成为 dict 的值,而 rest 将是关键,例如:

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.我想要一段代码来处理任何长度的任何列表,以便最后一个元素是值,rest 将是关键。 Thank you.谢谢你。

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

Try this one.试试这个。 It will work for any length of list :它适用于任何长度的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:使用 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 }结果: {“香蕉薯条”:12 }

This should do the trick:这应该可以解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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