简体   繁体   English

将嵌套列表转换为带有键和多个列表值(如果存在)的字典

[英]Convert nested list into dict with key and multiple list values if exist

I have a nested list as below.我有一个嵌套列表如下。 Since list is very huge and to reduce search time, thought would be better to convert as dict.由于列表非常庞大并且为了减少搜索时间,认为转换为字典会更好。

With innerlist[index] to be key and rest to be values.以 innerlist[index] 为键,rest 为值。 Incase key is occuring twice need to add list of values in dict. Incase 键出现两次需要在字典中添加值列表。

List列表

[
 ['001', 'xxxx', 'xxxx'], 
 ['002', '1', 'H', '0', 'H'], 
 ['002', '1', 'Z', '0', 'H']
]

Need Dict as follows需要Dict如下

   {
        '001': ['xxxx', 'xxxx'],
        '002': [
                ['1', 'H','0', 'H'],
                ['1', 'Z','0', 'H']
        ],
    }

I did it with following code, still seems not an optimum way for a huge list.我用下面的代码做到了,似乎仍然不是一个巨大列表的最佳方式。 Also for non duplicated item, I get nested list with 1 item.同样对于非重复项目,我得到包含 1 个项目的嵌套列表。 '001': [['xxxx', 'xxxx']], Let me know if a better way is possible. '001': [['xxxx', 'xxxx']], 让我知道是否有更好的方法。

data_dict = dict()
for data in bytes_data:
    if data[0] in data_dict:
        data_dict[data[0]].append(data[1:])
    else:
        data_dict[data[0]] = [data[1:]]

If you're in a recent Python version (3.5+ I think) you can do this more concisely like:如果您使用的是最新的 Python 版本(我认为是 3.5+),您可以更简洁地执行此操作,例如:

data = [
  ['001', 'xxxx', 'xxxx'],
  ['002', '1', 'H', '0', 'H'],
  ['002', '1', 'Z', '0', 'H']
]

data_dict = {}

for key, *vals in data:
    data_dict.setdefault(key, []).append(vals)

But I suggest benchmarking it, the code you have may be more efficient, especially if many of the keys do not have repeat entries in the src list.但我建议对其进行基准测试,您拥有的代码可能更有效,尤其是如果许多键在 src 列表中没有重复条目时。

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

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