簡體   English   中英

在python中創建一個字典列表

[英]Creating a list of dictionaries in python

我有一個從文本文件中讀入的以下數據集:

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

我需要創建一個字典列表如下:

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

我嘗試使用生成器函數,但很難創建一個列表。

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

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

一個內襯,只是為了好玩:

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]))

生產:

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

作為獎勵,這也適用於更長的序列:

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

輸出:

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

說明:

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))
  • [... for s in all_examples]對於列表中的每個元素:
  • s.split(',')[1:]用逗號分隔,然后在第一個之后取出每個元素
  • (...) for x in並將其轉換為元組列表
  • s[0], int(x)第一個字母的s[0], int(x) ,該元素轉換為整數
  • zip(*[...])現在轉置你的元組列表
  • map(dict, ...)並將每一個變成字典!

也只是為了好玩,但重點是可理解性:

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

將打印

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

只要輸入是帶有整數的csv並且行長度相同,就可以正常工作。

解剖:我將對A,B和C使用teminology“thing”,對數據中的“columns”使用“measurement”,即inut數據的相同“csv-column”中的那些值。

將字符串輸入數據放入每行的列表中: A,1,1 - > ["A","1","1"]

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

結果應該是一個dicts列表,所以讓我們初始化一個:

ld = list()

對於每個測量(假設所有行具有相同的列數):

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

從線上取出物品l[0] ,例如“A”,並將相應列l[col]中的測量的數值int() ,例如1,例如“1”,分配給物品。 然后使用字典理解將其組合到所需結果的下一行。 最后append() dict append()到結果列表ld

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

查看未消失的。 使用print json.dumps(ld, indent=4)可以更方便地顯示:

print ld

希望這可以幫助。 這里找到關於dict理解的更多信息 (這本偉大的書的Python3版本)。

您實際上有一個字符串列表,並且您希望有一個由每個字符串的元組三元組中的相同鍵生成的成對字典列表。

為了保持這個相對簡單,我將使用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'}]

你的問題應該是“如何列出詞典列表?”。 這是你想要考慮的事情。

>>> 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