简体   繁体   English

Python创建列表字典

[英]Python Create a Dictionary of Lists

Alright I searched, but I did not find an answer to my specific problem. 好吧,我进行了搜索,但没有找到具体问题的答案。 I am creating a dictionary of lists. 我正在创建列表字典。 I have while loop creating a few lists of values as well as a name to associate with it: 我在while循环中创建了一些值列表以及与其关联的名称:

dict = {} 
list = [1, 2]
name = key1
list = [3, 4]
name = key1

If the name is the same, the list will be appended to the existing set of values for the key. 如果名称相同,则列表将附加到键的现有值集之后。 Here is the code I have: 这是我的代码:

if key in dict:
    dict[key].append(list)
else:
    dict[key] = list

This is the output I want: 这是我想要的输出:

dictionary = {'key1': [1, 2], [3, 4]} 字典= {'key1':[1,2],[3,4]}

However I keep getting this output: 但是我一直得到以下输出:

dictionary = {'key1': [1, 2, [3, 4]]} 字典= {'key1':[1、2,[3、4]]}

where the second list to the key is being put inside of the first list. 该键的第二个列表放在第一个列表的内部。

This is a very common error. 这是一个非常常见的错误。 I am fairly certain that you are doing: 我相当确定您正在执行以下操作:

list1.append(list2)

Instead, you want to do: 相反,您想这样做:

list1.extend(list2)

Here is a very useful resource 这是一个非常有用的资源

However, since you want [[1,2], [3,4]] instead of [1,2,3,4] , you should do: 但是,由于要[[1,2], [3,4]]而不是[1,2,3,4] ,因此应执行以下操作:

if key in d1:
    d1[key].append(l1)
else:
    d1[key] = [l1]

That is because you are appending a list to a list each time. 这是因为您每次都将一个列表追加到一个列表中。 You need to use extend instead. 您需要改为使用扩展。 Code: 码:

keys = ['name1', 'name2', 'name2', 'name1']
somelist = [1, 2, 3]
d = {}
for k in keys:
   d.setdefault(k, []).extend(somelist)

You need a list of list in fact, your output will look like this: 实际上,您需要一个列表列表,您的输出将如下所示:

dictionary = {'key1': [[1, 2], [3, 4]]} 字典= {'key1':[[1,2],[3,4]]}

To have a key associated to multiple values you could use this line: 要使键与多个值关联,可以使用以下行:

dictionary.setdefault(key, []).append(a_list)

setdefault will associate the key to the default value [] if the key is not present in your dictionary. 如果字典中不存在键,则setdefault会将键与默认值[]关联。

Also you should avoid using dict or list to define your own variables, they are built-in and you are redefining them. 同样,您应该避免使用dictlist定义自己的变量,它们是built-in变量,您需要重新定义它们。

Edit 编辑

To make it obvious to the reader maybe this could help, its the output of an interative python session: 为了使读者明白,这可能会有所帮助,它是一个交互式python会话的输出:

>>> d = {}
>>> d.setdefault('key1', []).append([1, 2])
>>> d.setdefault('key1', []).append([3, 4])
>>> d
{'key1': [[1, 2], [3, 4]]}

I hope not misunderstand , since dictionary = {'key1': [1, 2], [3, 4]} is poorly expressed 我希望不要误解,因为字典= {'key1':[1,2],[3,4]}的表达不佳

def add2dict(d, l, k):
  if not k in d:
    dict[k] = []
  d[k].append(l)

dict = {} 
add2dict(dict, [1,2], "key1")
add2dict(dict, [3,4], "key1")

result in dict: 结果字典:

{'key1': [[1, 2], [3, 4]]} {'key1':[[1、2],[3、4]]}

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

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