簡體   English   中英

根據列表列表的長度為字典創建鍵

[英]Create keys for dictionary based on length of list of lists

我有以下列表:

my_list = [[['pd', 1],
           ['pd_de', None],
           ['pd_amnt', '$10.00']],
           [['pd', 1],
           ['pd_de', '5/1/19 '],
           ['pd_amnt', '$100.00 '],
           ['pd', 2],
           ['pd_de', '5/1/20 '],
           ['pd_amnt', '$200.00 ']],
           [['pd', 1],
           ['pd_de', None],
           ['pd_amnt', None]],
           [['pd', 1],
           ['pd_de', '5/1/19 '],
           ['pd_amnt', '$300.00 '],
           ['pd', 2],
           ['pd_de', '5/1/20 '],
           ['pd_amnt', '$600.00 '],
           ['pd', 3],
           ['pd_de', '6/1/18'],
           ['pd_amnt', '$450.00']]]

使用它,我想創建一個字典列表。 我在下面創建字典列表,

list_dict = []

for i in my_list:
    temp_dict = {}
    for j in i:
        temp_dict[j[0]] = j[1]
    list_dict.append(temp_dict)

我得到一個像這樣的 output,我不想要,

[{'pd': 1, 'pd_de': None, 'pd_amnt': '$10.00'},
 {'pd': 2, 'pd_de': '5/1/20 ', 'pd_amnt': '$200.00 '},
 {'pd': 1, 'pd_de': None, 'pd_amnt': None},
 {'pd': 3, 'pd_de': '6/1/18', 'pd_amnt': '$450.00'}]

我需要這樣的 output,

[{'pd_1': 1, 'pd_de_1': None, 'pd_amnt_1': '$10.00'},
 {'pd_1': 1, 'pd_de_1': '5/1/19', 'pd_amnt_1': '$100.00', 'pd_2': 2, 'pd_de_2': '5/1/20 ', 'pd_amnt_2': '$200.00 '},
 {'pd_1': 1, 'pd_de_1': None, 'pd_amnt_1': None},
 {'pd_1': 1, 'pd_de_1': '5/1/19', 'pd_amnt_1': '$300.00','pd_2': 2, 'pd_de_2': '5/1/20', 'pd_amnt': '$600.00','pd_3': 1, 'pd_de_3': '6/1/18', 'pd_amnt_3': '$450.00'}]

如果你在上面看到,當里面的列表長度為 3 時,它們是可以的。如果超過 3,那么它不會給出正確的結果。

當我為字典創建鍵時,我也不確定如何在鍵(即'pd_1')中創建"_"

如何實現我想要的 output?

(注意:不知道如何命名標題,我說的是列表長度,我可能錯了,因為我不熟悉pythonic術語)

保留項目的順序:

import pandas as pd
from collections import OrderedDict

# my_list = ...

res = []
for l1 in my_list:
    d = OrderedDict()
    for l2 in l1:
        if l2[0] == 'pd':
            sfx = l2[1]
        d[f'{l2[0]}_{sfx}'] = l2[1].strip() if isinstance(l2[1], str) else l2[1]
    res.append(d)

df = pd.DataFrame(res)
print(df)

output:

   pd_1 pd_de_1 pd_amnt_1  pd_2 pd_de_2 pd_amnt_2  pd_3 pd_de_3 pd_amnt_3
0     1    None    $10.00   NaN     NaN       NaN   NaN     NaN       NaN
1     1  5/1/19   $100.00   2.0  5/1/20   $200.00   NaN     NaN       NaN
2     1    None      None   NaN     NaN       NaN   NaN     NaN       NaN
3     1  5/1/19   $300.00   2.0  5/1/20   $600.00   3.0  6/1/18   $450.00

您可以使用附加變量( counter )來查找字典中尚不存在的鍵“索引”:

result = []
for sub_list in my_list:
    temp = {}
    for key, value in sub_list:
        counter = 1
        while f"{key}_{counter}" in temp:
            counter  += 1
        temp[f"{key}_{counter}"] = value
    result.append(temp)

更有效的解決方案是將計數器存儲到 dict 中,並在使用鍵后遞增它們:

result = []
for sub_list in my_list:
    counters = {}
    temp = {}
    for key, value in sub_list:
        if key in counters:
            counters[key] += 1
        else:
            counters[key] = 1
        temp[f"{key}_{counters[key]}" ] = value
    result.append(temp)

使用collections.defaultdict你可以把它寫得更短一點:

from collections import defaultdict

result = []
for sub_list in my_list:
    counters = defaultdict(int)
    temp = {}
    for key, value in sub_list:
        counters[key] += 1
        temp[f"{key}_{counters[key]}"] = value
    result.append(temp)
  • 我找到了一個非常酷的方法來做到這一點。
  • 您可以在每次看到它時使用defaultdict來增加鍵。 然后將其添加到您的result字典中。
list_dict = []

from collections import defaultdict

for i in my_list:
    temp_dict = {}
    incr = defaultdict(int)
    for j in i:
        incr[j[0]] += 1
        temp_dict[j[0] + '_' + str(incr[j[0]])] = j[1]
    list_dict.append(temp_dict)

Output:

[{'pd_1': 1, 'pd_de_1': None, 'pd_amnt_1': '$10.00'},
 {'pd_1': 1,
  'pd_de_1': '5/1/19 ',
  'pd_amnt_1': '$100.00 ',
  'pd_2': 2,
  'pd_de_2': '5/1/20 ',
  'pd_amnt_2': '$200.00 '},
 {'pd_1': 1, 'pd_de_1': None, 'pd_amnt_1': None},
 {'pd_1': 1,
  'pd_de_1': '5/1/19 ',
  'pd_amnt_1': '$300.00 ',
  'pd_2': 2,
  'pd_de_2': '5/1/20 ',
  'pd_amnt_2': '$600.00 ',
  'pd_3': 1,
  'pd_de_3': '6/1/18',
  'pd_amnt_3': '$450.00'}]

你得到這個的原因是當你在字典中設置一個鍵時,它會覆蓋任何以前的數據。 例如,你有這個字典x = ["a":1, "b":2, "c":3]如果你做x["d"] = 4它將是["a":1, "b":2, "c":3, "d":4]但如果你再做x["a"] = 3它將是["a":3, "b":2, "c":3, "d":4]
您的解決方案是將每個項目添加到字典中,標簽后帶有一個數字來表示它是哪個標簽。

list_dict = []

for i in my_list:
    temp_dict = {}
    for j in i:
        a = 1
        while j[0]+"_"+str(a) in temp_dict:
            a += 1
        temp_dict[j[0]+"_"+str(a)] = j[1]
    list_dict.append(temp_dict)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM