简体   繁体   中英

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. Incase key is occuring twice need to add list of values in dict.

List

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

Need Dict as follows

   {
        '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. '001': [['xxxx', 'xxxx']], Let me know if a better way is possible.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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