简体   繁体   English

将列表列表转换为具有多个键值的字典

[英]Converting list of lists to a dictionary with multiple values for a key

I need to write a function that accepts a list of lists representing friends for each person and need to convert it into a dictionary. 我需要编写一个函数来接受代表每个人朋友的列表列表,并需要将其转换为字典。 so an input of [['A','B'],['A','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']] should return {A:[B,C,D],B:[A],C:[B,D],D:[B],E:None} 所以输入[['A','B'],['A','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']]应该返回{A:[B,C,D],B:[A],C:[B,D],D:[B],E:None}

Input: 输入:

[['A','B'],['A','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']]

Expected Output: 预期产出:

{A:[B,C,D],B:[A],C:[B,D],D:[B],E:None}

Currently I am trying the following: 目前我正在尝试以下方法:

s=[['A','B'],['A','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']]

output=dict.fromkeys((set([x[0] for x in s])),[ ])

for x in s:
    if len(x)>1:
        output[x[0]].append(x[1])
    else:
        output[x[0]].append(None)

But the output is giving me all values for every key rather than returning only the corresponding values 但是输出给了我每个键的所有值,而不是只返回相应的值

The output i am getting is: 我得到的输出是:

{
'A': ['B', 'C', 'D', 'A', 'B', 'D', 'B', None],

 'B': ['B', 'C', 'D', 'A', 'B', 'D', 'B', None],

 'C': ['B', 'C', 'D', 'A', 'B', 'D', 'B', None],

 'D': ['B', 'C', 'D', 'A', 'B', 'D', 'B', None],

 'E': ['B', 'C', 'D', 'A', 'B', 'D', 'B', None]
}

You can iterate through the key-value pairs in the list of lists, but unpack the value as a list to accommodate the possible lack of a value: 您可以遍历列表列表中的键值对,但是将值解压缩为列表以适应可能缺少的值:

s = [['A','B'],['A','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']]
output = {}
for k, *v in s:
    if v:
        output.setdefault(k, []).extend(v)
    else:
        output[k] = None

output becomes: output变为:

{'A': ['B', 'C', 'D'], 'B': ['A'], 'C': ['B', 'D'], 'D': ['B'], 'E': None}

Or if you don't mind that keys without a value get an empty list instead of None , you can simply do: 或者,如果你不介意没有值的键得到一个空列表而不是None ,你可以简单地做:

output = {}
for k, *v in s:
    output.setdefault(k, []).extend(v)

output would then become: output将变为:

{'A': ['B', 'C', 'D'], 'B': ['A'], 'C': ['B', 'D'], 'D': ['B'], 'E': []}

You should use a common dict comprehension to initiate the dict : 您应该使用常见的字典理解来启动dict

output = {x[0]: [] for x in s}

dict.fromkeys gives all keys the identical referential value. dict.fromkeys为所有键提供相同的引用值。 With a mutable value that is a problem. 使用可变值是一个问题。 The comprehension will give each key an independent list object, in addition to being more readable. 除了更具可读性之外,理解还将为每个键提供一个独立的list对象。

The issue is the list you feed to dict.keys is only one reference across keys. 问题是您提供给dict.keys的列表只是键之间的一个引用。

Your desired result is inconsistent. 您想要的结果不一致。 I recommend you choose an empty list for 'E' , however much it seems None is more appropriate. 我建议你选择一个空列表'E' ,然而很多似乎 None更合适。 With this adjusted requirement, you can use collections.defaultdict . 通过此调整后的要求,您可以使用collections.defaultdict

from collections import defaultdict

L = [['A','B'],['E','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']]

dd = defaultdict(list)

for lst in L:
    if len(lst) > 1:
        dd[lst[0]].append(lst[1])
    else:
        dd[lst[0]]

print(dd)

defaultdict(list,
            {'A': ['B', 'C', 'D'],
             'B': ['A'],
             'C': ['B', 'D'],
             'D': ['B'],
             'E': []})

One of the way to solve this is as given below: 解决这个问题的方法之一如下:

friend_combi = [['A','B'],['A','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']]  # Input to be processed

final_dict = {} #Empty dict to store result
for i in friend_combi: # loop through each element in list
    if final_dict.get(i[0]):  #if data present in dict then append else add
        final_dict[i[0]].append(i[1])
    else:
        final_dict[i[0]] = [i[1]] if i[1:] else None #check if value exist in list else save None
print (final_dict)
#Output --> {'A': ['B', 'C', 'D'], 'B': ['A'], 'C': ['B', 'D'], 'D': ['B'], 'E': None}

I hope this helps :) 我希望这有帮助 :)

You can define a function named get_dictionary() as the below code shows. 您可以定义一个名为get_dictionary()的函数,如下面的代码所示。

>>> def get_dictionary(l):
...     d = {}
...     for arr in l:
...         if len(arr) == 2:
...             key = arr[0]
...             if key in d:
...                 d[key].append(arr[1])
...             else:
...                 d[key] = [arr[1]]
...         else:
...             d[key] = None
...     return d
...
>>> l = [['A','B'], ['A','C'], ['A','D'], ['B','A'], ['C','B'], ['C','D'], ['D','B'], ['E']]
>>>
>>> get_dictionary(l)
{'A': ['B', 'C', 'D'], 'B': ['A'], 'C': ['B', 'D'], 'D': None}
>>>

Pretty printing the dictionary as JSON. 将字典打印为JSON。

>>> import json
>>>
>>> d = get_dictionary(l)
>>>
>>> print(json.dumps(d, indent=4))
{
    "A": [
        "B",
        "C",
        "D"
    ],
    "B": [
        "A"
    ],
    "C": [
        "B",
        "D"
    ],
    "D": null
}
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM