简体   繁体   English

在python中创建一个字典列表

[英]Creating a list of dictionaries in python

I have a following data set that I read in from a text file: 我有一个从文本文件中读入的以下数据集:

all_examples=   ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

I need to create a list of dictionary as follows: 我需要创建一个字典列表如下:

lst = [ 
{"A":1, "B":2, "C":4, "D":4 },
{"A":1, "B":1, "C":4, "D":5 } 
]

I tried using an generator function but it was hard to create a list as such. 我尝试使用生成器函数,但很难创建一个列表。

attributes = 'A,B,C'
def get_examples():

    for value in examples:
        yield dict(zip(attributes, value.strip().replace(" ", "").split(',')))

A one liner, just for fun: 一个内衬,只是为了好玩:

all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))

Produces: 生产:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, 
 {'A': 1, 'C': 4, 'B': 1, 'D': 5}]

As a bonus, this will work for longer sequences too: 作为奖励,这也适用于更长的序列:

all_examples = ['A,1,1,1', 'B,2,1,2', 'C,4,4,3', 'D,4,5,6']

Output: 输出:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4},
 {'A': 1, 'C': 4, 'B': 1, 'D': 5},
 {'A': 1, 'C': 3, 'B': 2, 'D': 6}]

Explanation: 说明:

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))
  • [... for s in all_examples] For each element in your list: [... for s in all_examples]对于列表中的每个元素:
  • s.split(',')[1:] Split it by commas, then take each element after the first s.split(',')[1:]用逗号分隔,然后在第一个之后取出每个元素
  • (...) for x in and turn it into a list of tuples (...) for x in并将其转换为元组列表
  • s[0], int(x) of the first letter, with that element converted to integer s[0], int(x)第一个字母的s[0], int(x) ,该元素转换为整数
  • zip(*[...]) now transpose your lists of tuples zip(*[...])现在转置你的元组列表
  • map(dict, ...) and turn each one into a dictionary! map(dict, ...)并将每一个变成字典!

Also just for fun, but with a focus on understandability: 也只是为了好玩,但重点是可理解性:

all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
ll = [ x.split(",") for x in all_examples ]
ld = list()
for col in range(1, len(ll[0])):
    ld.append({ l[0] : int(l[col]) for l in ll })
print ld

will print 将打印

[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]

Works as long as the input is csv with integers and lines are same length. 只要输入是带有整数的csv并且行长度相同,就可以正常工作。

Dissection: I will use the teminology "thing" for A, B and C and "measurement" for the "columns" in the data, ie those values in the same "csv-column" of the inut data. 解剖:我将对A,B和C使用teminology“thing”,对数据中的“columns”使用“measurement”,即inut数据的相同“csv-column”中的那些值。

Get the string input data into a list for each line: A,1,1 -> ["A","1","1"] 将字符串输入数据放入每行的列表中: A,1,1 - > ["A","1","1"]

ll = [ x.split(",") for x in all_examples ]

The result is supposed to be a list of dicts, so let's initialize one: 结果应该是一个dicts列表,所以让我们初始化一个:

ld = list()

For each measurement (assuming that all lines have the same number of columns): 对于每个测量(假设所有行具有相同的列数):

for col in range(1, len(ll[0])):

Take the thing l[0] , eg "A", from the line and assign the numeric value int() , eg 1, of the measurement in the respective column l[col] , eg "1", to the thing. 从线上取出物品l[0] ,例如“A”,并将相应列l[col]中的测量的数值int() ,例如1,例如“1”,分配给物品。 Then use a dictionary comprehension to combine it into the next line of the desired result. 然后使用字典理解将其组合到所需结果的下一行。 Finally append() the dict to the result list ld . 最后append() dict append()到结果列表ld

    ld.append({ l[0] : int(l[col]) for l in ll })

View unfoamtted. 查看未消失的。 Use print json.dumps(ld, indent=4) for more convenient display: 使用print json.dumps(ld, indent=4)可以更方便地显示:

print ld

Hope this helps. 希望这可以帮助。 Find more on dict comprehensions eg here (Python3 version of this great book). 这里找到关于dict理解的更多信息 (这本伟大的书的Python3版本)。

You actually have a list of strings, and you'd like to have a list of paired dictionaries generated from the same key in the tuple triplets of each string. 您实际上有一个字符串列表,并且您希望有一个由每个字符串的元组三元组中的相同键生成的成对字典列表。

To keep this relatively simple, I'll use a for loop instead of a complicated dictionary comprehension structure. 为了保持这个相对简单,我将使用for循环而不是复杂的字典理解结构。

my_dictionary_list = list()
d1 = dict()
d2 = dict()
for triplet_str in all_examples:
    key, val1, val2 = triplet_str.split(',')
    d1[key] = val1
    d2[key] = val2
my_dictionary_list.append(d1)
my_dictionary_list.append(d2)

>>> my_dictionary_list
my_dictionary_list
[{'A': '1', 'B': '2', 'C': '4', 'D': '4'},
 {'A': '1', 'B': '1', 'C': '4', 'D': '5'}]

Your question should be "How to crate list of dictionaries?". 你的问题应该是“如何列出词典列表?”。 Here's something you would like to consider. 这是你想要考虑的事情。

>>> dict={}
>>> dict2={}
>>> new_list = []
>>> all_examples=['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
>>> for k in all_examples:
...     ele=k.split(",")
...     dict[str(ele[0])]=ele[1]
...     dict[str(ele[0])]=ele[2]
...     new_list.append(dict)
...     new_list.append(dict2)
>>> dict
{'A': '1', 'C': '4', 'B': '2', 'D': '4'}
>>> dict2
{'A': '1', 'C': '4', 'B': '1', 'D': '5'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM