从单词中获取字符串列表

时间:2015-01-27 14:44:38

标签: python string list dictionary word

我正在尝试将包含字符串作为键和字符串列表的字典的项目反转为值:

dico = {'key1': [],
        'key2': [],
        'key3': ['value1', 'value1'],
        'key4': ['value2', 'value2'],
        'key5': ['value3'],
        'key6': ['value1', 'value2', 'value3']}

new_dict = {}

for key, values in dico.items():
    if values:
        for value in values:
            try:
                if key not in new_dict[value]:
                    new_dict[value].append(key)
            except KeyError:
                new_dict[values[0]] = list(key)
            else:
                print('ERROR')

这是预期的结果:

#Expected
new_dict = {'value1': ['key3', 'key6'],
            'value2': ['key4', 'key6'],
            'value3': ['key5', 'key6']}
#Reality
new_dict = {'value1': ["k", "e", "y", "3", "k", "e", "y", "6"],
            'value2': ["k", "e", "y", "4", "k", "e", "y", "6"],
            'value3': ["k", "e", "y", "5", "k", "e", "y", "6"]}

我注意到我改变了:

new_dict[values[0]] = list(key)

由此:

new_dict[values[0]] = []
new_dict[values[0]].append(key)

它实际上有效,但还有另一种方法可以在一行中完成吗?

2 个答案:

答案 0 :(得分:2)

您正在将钥匙转到列表:

new_dict[values[0]] = list(key)

这将产生一个包含单个字符的列表。改为使用列表文字:

new_dict[values[0]] = [key]

您可以使用dict.setdefault() method处理new_dict中缺少的密钥来简化代码。看起来你想要生成 sets ;设置跟踪唯一值并保存您必须对重复项进行显式测试。

for key, values in dico.items():
    for value in values:
        new_dict.setdefault(value, set()).add(key)

您可以随后将这些集转回列表:

new_dict = {key: list(values) for key, values in new_dict.items()}

演示:

>>> dico = {'key1': [],
...         'key2': [],
...         'key3': ['value1', 'value1'],
...         'key4': ['value2', 'value2'],
...         'key5': ['value3'],
...         'key6': ['value1', 'value2', 'value3']}
>>> new_dict = {}
>>> for key, values in dico.items():
...     for value in values:
...         new_dict.setdefault(value, set()).add(key)
... 
>>> new_dict
{'value3': set(['key6', 'key5']), 'value2': set(['key6', 'key4']), 'value1': set(['key3', 'key6'])}
>>> {key: list(values) for key, values in new_dict.items()}
{'value3': ['key6', 'key5'], 'value2': ['key6', 'key4'], 'value1': ['key3', 'key6']}

答案 1 :(得分:2)

  1. 从主dico词典中迭代每个项目。
  2. 检查是否存在值。
  3. 从值中迭代每个项目。
  4. 使用set方法删除重复值。
  5. 添加到new_dict字典,其中value为key,key为list value。
  6. 代码:

    dico = {'key1': [],
            'key2': [],
            'key3': ['value1', 'value1'],
            'key4': ['value2', 'value2'],
            'key5': ['value3'],
            'key6': ['value1', 'value2', 'value3']}
    
    new_dict = {}
    
    for key, values in dico.items():
        if values:
            for value in set(values):
                try:
                    new_dict[value].append(key)
                except:
                    new_dict[value] = [key]
    
    import pprint
    pprint.pprint(new_dict)
    

    输出:

    $ python test.py 
    {'value1': ['key3', 'key6'],
     'value2': ['key6', 'key4'],
     'value3': ['key6', 'key5']}