Python - 列表字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27770836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:14:11  来源:igfitidea点击:

Python - dictionary of lists

pythondictionary

提问by Elena

Which is the best way to make a dictionary of lists? For instance, if I have lists list1, list2and want to make a dictionary my_dictlike that:

哪个是制作列表字典的最佳方法?例如,如果我有列表list1、list2并且想要制作一个像这样的字典my_dict

my_dict = ['list1': list1, 'list2': list2]

I've found thisexample but the best answer is written in 2009. Maybe there are some new more laconic ways to do this?

我找到了这个例子,但最好的答案是在 2009 年写的。也许有一些新的更简洁的方法来做到这一点?

采纳答案by NPE

You need to use curly rather than square brackets, but otherwise this is probably as good as it gets:

您需要使用大括号而不是方括号,否则这可能就够了:

list1 = ['a', 'b', 'c']
list2 = [1, 2, 3, 4]
my_dict = {'list1': list1, 'list2': list2}

回答by msturdy

Use the curly brace syntax to define the dictionary, and give each entry in your dictionary a key that corresponds to each value:

使用花括号语法定义字典,并为字典中的每个条目指定一个对应于每个值的键:

list_a = [1,2,3,4,5]
list_b = [6,7,8,9,10]

my_dict = {'list1':list_a, 'list2':list_b}

More in the python docs

更多在 python 文档中

回答by Ashalynd

This should work:

这应该有效:

my_dict = dict([('list1', list1), ('list2', list2)])

Or, alternatively:

或者,或者:

my_dict = {'list1': list1, 'list2': list2}

The result will be the same.

结果将是相同的。

回答by Jeffery Opoku-Mensah

Try this method, very succinct. Curly braces, not square brackets.

试试这个方法,很简洁。花括号,不是方括号。

I think that's the shortest way around it.

我认为这是绕过它的最短方法。

list1 = [5, 500, 543]
list2 = [4, 4, 4]

my_dict = {'list1':list1, 'list2': list2}

回答by GGhe

If you want to turn the variable name into a key, here is a similar question.

如果你想把变量名变成一个键,这里有一个类似的问题

If you just want a dictionary of lists with a sequential key.

如果您只想要一个带有顺序键的列表字典。

def turn_to_dict(*args):
    return {i: v for i, v in enumerate(args)}

lst1 = [1, 2, 3, 4]
lst2 = [3, 4, 6, 7]
lst3 = [5, 8, 9]

v = turn_to_dict(lst1, lst2, lst3)

>>> print(v)
{0: [1, 2, 3, 4], 1: [3, 4, 6, 7], 2: [5, 8, 9]} 

回答by pylang

For a dictionary of lists, consider a defaultdict.

对于列表字典,考虑一个defaultdict.

A normal dictionaryworks fine, but it raises an error if a key is not found.

一个正常的字典工作正常,但如果关键是没有找到它提出了一个错误。

list1 = list("abcd")
list2 = [1, 2, 3, 4]


d = {"list1": list1, "list2": list2}
d["list3"]
# KeyError: 'list3'

This may be disruptive in some applications and may require additional exception handling.

这在某些应用程序中可能是破坏性的,并且可能需要额外的异常处理。

The defaultdictbehaves like a normal dict while adding some protection against errors.

defaultdict行为像一个正常的字典,同时增加对错误的一些保护。

import collections as ct


dd = ct.defaultdict(list)
dd.update(d)
dd
# defaultdict(list, {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]})

Adding a missing key will call the default factory function, i.e. list. Here instead of a error, we get an empty container:

添加缺少的键将调用默认的工厂函数,即list. 这里不是错误,而是一个空容器:

dd["list3"]
# []

This entry was added with an empty list.

添加此条目时带有一个空列表。

dd
# defaultdict(list,
#             {'list1': ['a', 'b', 'c', 'd'],
#              'list2': [1, 2, 3, 4],
#              'list3': []})

Convert a defaultdictto a regular dict by setting the default factory to None

defaultdict通过将默认工厂设置为将 a 转换为常规 dictNone

dd.default_factory = None
dd
# defaultdict(None, {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]})

or by using the dict()builtin:

或通过使用dict()内置:

dict(dd)
# {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]}