如何将列表的dict值转换为元组,然后将dict求反

时间:2019-05-30 22:13:12

标签: python-3.x list dictionary tuples

我的作业需要创建一个字典,其中包含每个键的值列表。然后,它提供了一个反转函数,并要求修改该函数,以便列表中的每个项目都是一个新键。我的理解是这样。 a = {'a':['2','3','4'],'b':['1','5','6']} b = {'2':'a','3':'a','4':'a','1':'b','5':'b','6':'b' }

我用元组而不是列表创建了一个测试字典,我能够将它们反转,但是我不知道如何将字典中的列表变成元组,然后变成对应于相同值的单个项目。 我看了YouTube教程,并尝试使用Google谷歌搜索(包括堆栈溢出),但无法获取完成的方法。 在这一点上,我什至一无所知-我感到非常困惑,对此我将不胜感激。


def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

#my initial dictionary
work_contacts={'Lauren' : '617-111-2222', 'Sana' : '781-234-1212', 'Kelly': '845-234-1515', 'Jose' : '946-999-3210', 'Sabrina' : '617-222-5656', 'Shirika' : '410-231-9090', 'Rachel': '823-432-2121'}

c=invert_dict(work_contacts)
c
{'617-111-2222': ['Lauren'], '781-234-1212': ['Sana'], '845-234-1515': ['Kelly'], '946-999-3210': ['Jose'], '617-222-5656': ['Sabrina'], '410-231-9090': ['Shirika'], '823-432-2121': ['Rachel']}
c['617-111-2222'] #calling the first key
['Lauren']

#the dictionary for the assignment
work_contacts={'Lauren' : ['617-111-2222', 'lauren@company.org'], 'Sana' : ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose' : ['946-999-3210', 'jose@company.org'], 'Sabrina' : ['617-222-5656', 'sabrina@company.org'], 'Shirika' : ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#the error comes back like this
invert_dict(work_contacts)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    invert_dict(work_contacts)
  File "<pyshell#2>", line 5, in invert_dict
    if val not in inverse:
TypeError: unhashable type: 'list'

#I tried to turn the lists into tuples
def l_t(s):
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return s

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

def l_t(s):
    p=s
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

`def l_t(s):
    p=s
    final = []
    for k, v in p.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#I then tried to tuple the values 
tuple(work_contacts.values())
(['617-111-2222', 'lauren@company.org'], ['781-234-1212', 'sana@company.org'], ['845-234-1515', 'kelly@company.org'], ['946-999-3210', 'jose@company.org'], ['617-222-5656', 'sabrina@company.org'], ['410-231-9090', 'shirika@comoany.org'], ['823-432-2121', 'rachel@company.org'])

#I have generated much more code with error messages, as below
b=invert_dict(test)
b
{(2, 'al', 3): ['a'], ('we', 'as', 4): ['blue']}

b[2]
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    b[2]
KeyError: 2
b(2)
Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    b(2)
TypeError: 'dict' object is not callable
b(2, 'al', 3)
Traceback (most recent call last):
  File "<pyshell#147>", line 1, in <module>
    b(2, 'al', 3)
TypeError: 'dict' object is not callable
b[1]
Traceback (most recent call last):
  File "<pyshell#148>", line 1, in <module>
    b[1]
KeyError: 1```

2 个答案:

答案 0 :(得分:0)

我不清楚您要解决什么。

但是,如果您尝试转换以下内容

{'a': [2, 3, 5], 'b': [7,11]} => {2: ['a'], 3: ['a'], 5: ['a'], 7: ['b'], 11: ['b']}

然后您可以使用以下内容

{v1: [k] for k, v in original_dict.items() for v1 in v}

一些多余的单词 反转我按照

遍历原始字典的字典
for k, v in original_dict.items() => ('a', [2, 3, 5]), ('b', [7,11])

第二步是遍历值v

[m for k in [[1,2], [3,4]] for m in k] => [1,2,3,4]

此步骤还显示了列表理解的工作原理-我们可以在其中循环访问嵌套列表。

您现在拥有所有工具,以了解如何使用相同的逻辑来创建字典。

答案 1 :(得分:0)

我相信您在问如何将invert_dict修改为可在第二个work_contacts字典上使用的函数,该字典以列表作为其值。如果没有,请忽略此答案!

让我们看一下功能:

def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

如果d具有列表作为其值,则val将是一个列表。这行:

if val not in inverse:

是函数抛出错误的地方。列表不能用作字典中的键;在Python的行话中,list是不可散列的类型。这就是错误所抱怨的。

如果您希望倒排字典中的键成为列表的元素,而不是列表本身,则只需要遍历列表,并对其元素做与原始{{ 1}}。尝试一些涉及以下方面的事情:

val
相关问题