Python:将多个列表转换为字典数组

时间:2015-12-12 05:33:08

标签: python arrays dictionary

想象一下,您有以下列表。

name = ['bob', 'kate', 'john']
age = [35, 12, 57]
gender = ["Male", "Female", "Male"]

如何将其转换为字典数组?

[
  {
    "name": "bob"
    "age": 35
    "gender": "Male"
  },
  {
    "name": "kate"
    "age": 12
    "gender": "Female"
  },
  {
    "name": "john"
    "age": 57
    "gender": "Male"
  }
]

6 个答案:

答案 0 :(得分:2)

使用简单的循环看起来像:

name = ['bob', 'kate', 'john']
age = [35, 12, 57]
gender = ["Male", "Female", "Male"]

list=[]

for i in range(len(name)):
  temp={}
  temp['name']=name[i]
  temp['age']=age[i]
  temp['gender']=gender[i]
  list.append(temp)

答案 1 :(得分:2)

一种通用方法,适用于具有可自定义字段名称的任意数量的列表

import pprint
def make_complex(**kwargs):
    return [dict(zip(kwargs.keys(), a)) for a in zip(*kwargs.values())]

name = ['bob', 'kate', 'john']
age = [35, 12, 57]
gender = ["Male", "Female", "Male"]

l = make_complex(name=name, age=age, gender=gender)
pprint.pprint(l)

l = make_complex(user=name, year=age, sex=gender)
pprint.pprint(l)

输出:

[{'age': 35, 'gender': 'Male', 'name': 'bob'},
 {'age': 12, 'gender': 'Female', 'name': 'kate'},
 {'age': 57, 'gender': 'Male', 'name': 'john'}]
[{'sex': 'Male', 'user': 'bob', 'year': 35},
 {'sex': 'Female', 'user': 'kate', 'year': 12},
 {'sex': 'Male', 'user': 'john', 'year': 57}]

答案 2 :(得分:1)

使用zipList comprehension

<强>代码:

name = ['bob', 'kate', 'john']
age = [35, 12, 57]
gender = ["Male", "Female", "Male"]

dic= [ {"name":val[0], "age":val[1], "gender":val[2]} for val in zip(name, age, gender)]

<强>输出:

[{'name':'bob','age':35,'gender':'Male'},
 {'name':'kate','age':12,'gender':'Female'},
 {'name':'john','age':57,'gender':'Male'}]

答案 3 :(得分:1)

使用列表理解和itertools

import itertools    

d = [{'name': n, 'age': a, 'gender': g} for n, a, g in itertools.izip(name, age, gender)]

答案 4 :(得分:1)

使用列表理解。

In [3]: [{"name":n,"age":a,"gender":g} for n,a,g in zip(name, age, gender)]
Out[3]:
[{'age': 35, 'gender': 'Male', 'name': 'bob'},
 {'age': 12, 'gender': 'Female', 'name': 'kate'},
 {'age': 57, 'gender': 'Male', 'name': 'john'}]

,或者

In [5]: [dict(zip(['name','age','gender'], t)) for t in zip(name, age, gender)]
Out[5]:
[{'age': 35, 'gender': 'Male', 'name': 'bob'},
 {'age': 12, 'gender': 'Female', 'name': 'kate'},
 {'age': 57, 'gender': 'Male', 'name': 'john'}]

答案 5 :(得分:1)

去吧。

name = ['bob', 'kate', 'john']
age = [35, 12, 57]
gender = ["Male", "Female", "Male"]
keys = [name, age, gender] #If there are more data to be added just change this one place

def get_var_name(var):
    for k, v in list(globals().iteritems()):
        if v is var:
            return k

d = []
for i in range(len(keys[0])):
    d.append({})
    for key in keys:
       d[i][get_var_name(key)] = key[i] 

print d

或者使用dict理解来避免内循环

d = []
for i in range(len(name)):
    d.append({get_var_name(key):key[i] for key in keys})
print d

为了使它成为一个班轮,结合dict理解内部和列表理解外部

print [{get_var_name(key):key[i] for key in keys} for i in range(len(keys[0]))]