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