[英]Having two lists as a value to a single key: Dictionaries
Looking for a way to add two lists to a value in a dictionary for example if want to add two lists to a single value for example 寻找一种将两个列表添加到字典中的值的方法,例如,如果要将两个列表添加到单个值中,例如
For example this dictionary dict1 = {a: [], b:[], c:[]}
例如,此字典
dict1 = {a: [], b:[], c:[]}
Would become dict1 = {a:([1,3,4,5,6],[1,2,3,4]),b:[],c:[]}
将变成
dict1 = {a:([1,3,4,5,6],[1,2,3,4]),b:[],c:[]}
When you add the two lists [1,2,3,4,5,6]
and [1,2,3,4]
to the key a
. 当您将两个列表
[1,2,3,4,5,6]
和[1,2,3,4]
到键a
。 And if you were to print the key a
you would get the two lists as output 如果要打印密钥
a
,则将得到两个列表作为输出
Any help would be much appreciated 任何帮助将非常感激
You can use list.append()
because your dict1['a']
's value is a list
. 您可以使用
list.append()
因为您的dict1['a']
的值是一个list
。 See this example: 请参阅以下示例:
dict1 = {'a': [], 'b':[], 'c':[]}
a = [1,2,3,4,5,6]
b = [1,2,3,4]
dict1['a'].append(a)
dict1['a'].append(b)
print(dict1)
Output: 输出:
{'a': [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4]], 'b': [], 'c': []}
you can also doing it in this way by adding two list [a]+[b]
您也可以通过添加两个列表
[a]+[b]
Edit: from the comment. 编辑:从评论。 Another better way
[a,b]
另一个更好的方法
[a,b]
dict1 = {'a': [], 'b':[], 'c':[]}
a = [1,2,3,4,5,6]
b = ['a','b']
dict1['a']=[a]+[b]
print(dict1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.