从Python列表中创建字典,列表中的第一项作为标题

时间:2018-11-06 20:20:22

标签: python

我正在尝试使用以下列表创建词典列表。

a = [["Name","Mary","Tom","John"],["Age","21","23","12"],["Gender","F","M","M"]]

我希望输出为:

a_list=[{"Name":"Mary", "Age":"21", "Gender":"F"},{"Name":"Tom", "Age":"23", "Gender":"M"},{"Name":"John", "Age":"12", "Gender":"M"}]

我尝试使用zip,但无法正常使用。请帮忙!

7 个答案:

答案 0 :(得分:5)

首先,我们可以拉出标头条目,以便只剩下值:

headers, values = zip(*((x[0], x[1:]) for x in a))
print(headers, values)
# ('Name', 'Age', 'Gender') (['Mary', 'Tom', 'John'], ['21', '23', '12'], ['F', 'M', 'M'])

然后我们可以zip合并值,然后zip将其中每个三元组与headers组合成字典:

print([dict(zip(headers, triple)) for triple in zip(*values)])
# [{'Name': 'Mary', 'Age': '21', 'Gender': 'F'}, {'Name': 'Tom', 'Age': '23', 'Gender': 'M'}, {'Name': 'John', 'Age': '12', 'Gender': 'M'}]

答案 1 :(得分:4)

a_list = []
for i in range(1, len(a[0])):
    diction = {}
    diction[a[0][0]] = a[0][i]
    diction[a[1][0]] = a[1][i]
    diction[a[2][0]] = a[2][i]
    a_list.append(diction)

答案 2 :(得分:2)

list(map(dict, zip(*([(k, i) for i in v] for k, *v in a))))

这将返回:

[{'Name': 'Mary', 'Age': '21', 'Gender': 'F'}, {'Name': 'Tom', 'Age': '23', 'Gender': 'M'}, {'Name': 'John', 'Age': '12', 'Gender': 'M'}]

答案 3 :(得分:2)

这是我建议的简单解决方案:

zipped_a = zip(*a)
keys = next(zipped_a)
dicts = [dict(zip(keys, values)) for values in zipped_a]

将键从a_zipped迭代器中拉出的另一种方法是在嵌套循环中使用它。外循环的第一次迭代获取键,而内循环则获取每组值。不幸的是,这种方法乍一看并不明显:

a_zipped = zip(*a)
dicts = [dict(zip(keys, values)) for keys in a_zipped for values in a_zipped]

zip(*a)拔出密钥的另一种方法是使用iterable unpacking。很明显,但是确实会创建一个额外的列表(all_values):

keys, *all_values = zip(*a)
dicts = [dict(zip(keys, values)) for values in all_values]

然后有一个愚蠢的单线:

dicts = [dict(zip(k, v)) for k, *zv in [zip(*a)] for v in zv]

原始答案:

有时候,多行解决方案可能很简单:

# make an iterator for each list
iters = list(map(iter, a))
# pull off first item from each iterator to use as keys        
keys = list(map(next, iters))
# zip the iterators so they are grouped as values, 
# then zip keys and values to make tuples for dict constructor
dicts = [dict(zip(keys, values)) for values in zip(*iters)]

答案 4 :(得分:1)

为此,我们可以使用pandas,在我们指定做什么而不是做什么 how 的意义上,它更具“声明性”

import pandas as pd

result = pd.DataFrame({k: v for k, *v in a}).to_dict('records')
对于给定的a

给出:

>>> pd.DataFrame({k: v for k, *v in a}).to_dict('records')
[{'Name': 'Mary', 'Age': '21', 'Gender': 'F'}, {'Name': 'Tom', 'Age': '23', 'Gender': 'M'}, {'Name': 'John', 'Age': '12', 'Gender': 'M'}]

答案 5 :(得分:1)

种类繁多的丑陋的内衬:

首先将每个内部列表的第一个元素三倍,然后将其与其余元素一起压缩,然后对未包装的内部元组进行压缩,以将其放入字典中:

a = [["Name","Mary","Tom","John"],["Age","21","23","12"],["Gender","F","M","M"]]

k = list(dict (o) for o in  zip(*[ zip(l[0:1]*3,l[1:]) for l in a] ))
print(k)

输出:

[{'Gender': 'F', 'Age': '21', 'Name': 'Mary'}, 
 {'Gender': 'M', 'Age': '23', 'Name': 'Tom'}, 
 {'Gender': 'M', 'Age': '12', 'Name': 'John'}]

答案 6 :(得分:1)

您可以使用extended iterable unpacking

a = [["Name", "Mary", "Tom", "John"], ["Age", "21", "23", "12"], ["Gender", "F", "M", "M"]]
result = [dict(val) for val in zip(*([(header, value) for value in values] for header, *values in a))]
print(result)

输出

[{'Gender': 'F', 'Name': 'Mary', 'Age': '21'}, {'Gender': 'M', 'Name': 'Tom', 'Age': '23'}, {'Gender': 'M', 'Name': 'John', 'Age': '12'}]