如何从仅包含键和键-值对列表的列表中创建字典(Python)? [英] How to create a dictionary from a list with a list of keys only and key-value pairs (Python)?

查看:578
本文介绍了如何从仅包含键和键-值对列表的列表中创建字典(Python)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此问题的扩展:如何在列表中拆分字符串以在Python中创建键值对

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

The difference from the above question is the items in my list are not all key-value pairs; some items need to be assigned a value.

我有一个列表:

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

我想创建一个字典:

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

我在想一些类似的事情:

I was thinking something along the lines of:

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]并提取前两个元素.这样,当没有值时将使用1:

For each split "pair", you can append [1] and extract the first 2 elements. This way, 1 will be used when there isn't a value:

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

这篇关于如何从仅包含键和键-值对列表的列表中创建字典(Python)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆