我有一個看起來像這樣的 csv 檔案:
apple 12 yes
apple 15 no
apple 19 yes
我想使用水果作為鍵并將該行的其余部分轉換為一個值串列,所以它看起來像:
{'apple': [[12, 'yes'],[15, 'no'],[19, 'yes']]}
當我想組合資料時,下面的代碼示例將每一行轉換為自己的字典。
import csv
fp = open('fruits.csv', 'r')
reader = csv.reader(fp)
next(reader,None)
D = {}
for row in reader:
D = {row[0]:[row[1],row[2]]}
print(D)
我的輸出看起來像:
{'apple': [12,'yes']}
{'apple': [15,'no']}
{'apple': [19,'yes']}
uj5u.com熱心網友回復:
D您的問題是您在每次迭代中都重置。不要那樣做。
請注意,輸出可能看起來與您想要的有些相關,但實際上并非如此。如果您D在此代碼完成運行后檢查變數,您會看到它僅包含您設定為的最后一個值:
{'apple': [19,'yes']}
相反,每當您遇到新水果時,將鍵添加到字典中。此鍵的值將是一個空串列。然后將您想要的資料附加到這個空串列中。
import csv
fp = open('fruits.csv', 'r')
reader = csv.reader(fp)
next(reader,None)
D = {}
for row in reader:
if row[0] not in D: # if the key doesn't already exist in D, add an empty list
D[row[0]] = []
D[row[0]].append([row[1:]]) # append the rest of this row to the list in the dictionary
print(D) # print the dictionary AFTER you finish creating it
或者,定義D為 acollections.defaultdict(list)并且您可以跳過整個if塊
請注意,在單個字典中,一個鍵只能有一個值。不能有多個值分配給同一個鍵。在這種情況下,每個水果名稱(鍵)都有一個分配給它的串列值。該串列包含更多串列,但這對字典無關緊要。
uj5u.com熱心網友回復:
您可以混合使用排序和分組:
from itertools import groupby
from operator import itemgetter
_input = """apple 12 yes
apple 15 no
apple 19 yes
"""
entries = [l.split() for l in _input.splitlines()]
{key : [values[1:] for values in grp] for key, grp in groupby( sorted(entries, key=itemgetter(0)), key=itemgetter(0))}
在 groupby 之前應用排序以獲得不重復的鍵,并且兩者的鍵都是取每一行的第一個元素。
uj5u.com熱心網友回復:
您遇到的部分問題是,您不是通過追加“添加”資料,D[key]而是替換它。最后你只得到每個鍵的最后一個結果。
您可能會將collections.defaultdict(list)其視為一種策略來初始化D或使用setdefault(). 在這種情況下,我將直接使用setdefault()它,但不要defaultdict()在更復雜的場景中打折。
data = [
["apple", 12, "yes"],
["apple", 15, "no"],
["apple", 19, "yes"]
]
result = {}
for item in data:
result.setdefault(item[0], []).append(item[1:])
print(result)
這應該給你:
{
'apple': [
[12, 'yes'],
[15, 'no'],
[19, 'yes']
]
}
如果您熱衷于尋找defaultdict()基于它的解決方案,可能如下所示:
import collections
data = [
["apple", 12, "yes"],
["apple", 15, "no"],
["apple", 19, "yes"]
]
result = collections.defaultdict(list)
for item in data:
result[item[0]].append(item[1:])
print(dict(result))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456010.html
標籤:Python python-3.x 列表 字典
