将不同长度的元组列表转换成字典

时间:2020-08-27 22:28:32

标签: python list dictionary tuples

我是python的新手,无法弄清楚如何将列表“ groups”转换为字典“ groups_dic”,这样,将每个元组字符串都分配为“ group_dic”中的键

groups = [("starch"), ("nuts", "vegetable"), ("fruits"), ("meat"), ("fruits"), ("starch")]
groups_dic = {}

这是我想要的消除重复字符串的结果:-

>>> print(groups_dic)

{"starch" : None,
"nuts" : None,
"vegetable" : None,
"fruits" : None,
"meat" : None}

4 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,这是一种非常简单的方法,基本上可以为给定字符串列表和/或字符串元组的字典收集唯一键

groups = [("starch"), ("nuts", "vegetable"), ("fruits"), ("meat"), ("fruits"), ("starch")]
groups_dic = {}


for group in groups:
  if type(group) != tuple:
    groups_dic[group] = None
  else:
    for element in group:
      groups_dic[element] = None

您将如何使用字典?您只是在尝试收集独特的元素吗?如果是这样,您可以使用集合而不是字典。

答案 1 :(得分:1)

您可以使用itertools.chaindict.fromkeys

from itertools import chain

groups = [("starch",), ("nuts", "vegetable"), ("fruits",), ("meat",), ("fruits",), ("starch",)]
res = dict.fromkeys(chain.from_iterable(groups))
print(res)

输出:

{'starch': None, 'nuts': None, 'vegetable': None, 'fruits': None, 'meat': None}

答案 2 :(得分:0)

假设您具有此元组列表

groups = [
    ("starch",),
    ("nuts","vegetable"),
    ("fruits",),
    ("meat",),
    ("fruits",),
    ("starch",),
]

您可以使用以下一线:

groups_dic = dict((string,None) for group in groups for string in group)
print(groups_dic)

groups_dic = {string:None for group in groups for string in group}
print(groups_dic)

答案 3 :(得分:0)

有一些for循环和条件:

for grp in groups:
    if type(grp) == tuple:
        for i in grp:
            if i not in groups_dic:
                groups_dic[i] = None
    elif type(grp) == str:
        if grp not in groups_dic:
            groups_dic[grp.replace('(','').replace(')','')]=None
                       
print(groups_dic)