将多个列表转换为字典

时间:2017-10-04 21:09:07

标签: python python-2.7 dictionary

我不确定这是否可行,但有没有办法将3个列表组合成字典,以便列表名称是键,项目列表是值?

示例:

输入

list1 = ['a', 'b', 'c'] 
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

输出:

dict = {
  'list1': ['a', 'b', 'c'],
  'list2': ['d', 'e', 'f'],
  'list3': ['g', 'h', 'i']
}

感谢

2 个答案:

答案 0 :(得分:3)

如果您能够在自己的功能中定义列表,
(所以它们是本地函数中唯一的变量),
你可以这样做:

def loc():    
  list1 = ['a', 'b', 'c']
  list2 = ['d', 'e', 'f']
  list3 = ['g', 'h', 'i']

  list_dictionary = (locals())

  print(list_dictionary)

loc()
  

{' list1':[' a',' b',' c'],' list2' :[' d',' e'' f'],' list3':[' g',& #39; h',' i']}

否则,你可能需要采取更像这样的东西:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']    
list3 = ['g', 'h', 'i']

list_dictionary = {}
for i in ('list1', 'list2', 'list3'):
  list_dictionary[i] = locals()[i]

print (list_dictionary)
  

{' list1':[' a',' b',' c'],' list2' :[' d',' e'' f'],' list3':[' g',& #39; h',' i']}

来源:https://stackoverflow.com/a/3972978/5411817

如果你的变量名是重复的,就像在例子中一样,你可以为变量名组成一个字符串列表:

variable_names_as_strings = []
for i in range(1,4):
    variable_names_as_strings.append('list' + str(i))

然后创建你的字典:

for i in variable_names_as_strings:
  list_dictionary[i] = locals()[i]
print (list_dictionary)
  

{' list1':[' a',' b',' c'],' list2' :[' d',' e'' f'],' list3':[' g',& #39; h',' i']}

<小时/> 有关locals()的更多信息(也可查询globals()):
https://www.programiz.com/python-programming/methods/built-in/locals https://docs.python.org/3.3/library/functions.html#locals

答案 1 :(得分:0)

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

dictionary = dict()

dictionary['list1'] = list1
dictionary['list2'] = list2
dictionary['list3'] = list3

print(dictionary)

输出:

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}