gpt4 book ai didi

python - 如何从仅包含键列表和键值对的列表创建字典(Python)?

转载 作者:太空狗 更新时间:2023-10-30 01:42:39 26 4
gpt4 key购买 nike

这是这个问题的扩展:How to split a string within a list to create key-value pairs in Python

与上述问题不同的是,我列表中的项目并不都是键值对;有些项目需要分配一个值。

我有一个列表:

list = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']

我想创建一个字典:

dict = { 'abc':'ddd', 'ef':1, 'ghj':1, 'jkl':'yui', 'rty':1 }

我的思路是这样的:

a = {}
for item in list:
if '=' in item:
d = item.split('=')
a.append(d) #I don't I can do this.
else:
a[item] = 1 #feel like I'm missing something here.

最佳答案

对于每个拆分“对”,您可以附加 [1] 并提取前 2 个元素。这样,当没有值时将使用 1:

print dict((s.split('=')+[1])[:2] for s in l)

关于python - 如何从仅包含键列表和键值对的列表创建字典(Python)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com