0

With the below data which convert list to dict:

store=[['hostname ', ' ABCD'], ['fsystem ', ' /dev/sdb'], ['actual_size ', ' 2.5T'], ['hostname ', ' XYZ'], ['fsystem ', ' /dev/sdb'], ['actual_size ', ' 2.5T']]

Please help/advise me as how I can convert the above List to Dict?

I tried with below code but it is not giving me expected output

for i in store:
    print(dict(zip(i,i)))
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Shrikant
  • 13
  • 5

2 Answers2

0
import json
b={'description': [['hostname ', ' ABC'], ['fsystem ', ' /dev/sdb'], ['actual_size ', ' 2.5T'], ['used_disk ', ' 486G'], ['avail_disk ', ' 1.9T'], ['percentage ', ' 21'], ['mount_disk ', ' /data'], ['hostname ', ' XYZ'], ['fsystem ', ' /dev/sdb'], ['actual_size ', ' 2.5T'], ['used_disk ', ' 533G'], ['avail_disk ', ' 1.8T'], ['percentage ', ' 23%'], ['mount_disk ', ' /data'], ['hostname ', ' MNOP'], ['fsystem ', ' /dev/sdb'], ['actual_size ', ' 2.5T'], ['used_disk ', ' 664G'], ['avail_disk ', ' 1.7T'], ['percentage ', ' 29%'], ['mount_disk ', ' /data']]}
b=(b['description'])

size = len(b)
idx_list = [idx + 1 for idx, val in enumerate(b) if 'mount_disk ' in val] #note the blank space!!!!
res = [dict(b[i: j]) for i, j in
    zip([0] + idx_list, idx_list + 
    ([size] if idx_list[-1] != size else []))]  
JSONarray=json.dumps(res) # or json.dump(...) to write the output in a new file

to check your new array of JSON objects:

print("now you have this list of JSON objects : " + str(res)) 

I would like to note that any feedback would be really appreciated, even just to clearify if you already have already solved your issue.

the split in multiple lists is adapted from: https://www.geeksforgeeks.org/python-split-list-into-lists-by-particular-value/

Edit:

I've now looked at your other questions in stackoverflow which make me think you weren't asking for fixing your inner lists to dicts but just a plain dict to json conversion. I can't understand how a json in that format may help you, but if that's the case you should specify it in your question. Looking at that dict format is very misleading.

Edit2

just:

store=[['hostname ', ' ABCD'], ['fsystem ', ' /dev/sdb'], ['actual_size ', ' 2.5T'], ['hostname ', ' XYZ'], ['fsystem ', ' /dev/sdb'], ['actual_size ', ' 2.5T']]
size = len(store)
idx_list = [idx + 1 for idx, val in enumerate(store) if 'actual_size ' in val] #note the blank space!!!!
storeNew = [dict(store[i: j]) for i, j in zip([0] + idx_list, idx_list + ([size] if idx_list[-1] != size else []))]  
storeNew #[{'actual_size ': ' 2.5T', 'fsystem ': ' /dev/sdb', 'hostname ': ' ABCD'},{'actual_size ': ' 2.5T', 'fsystem ': ' /dev/sdb', 'hostname ': ' XYZ'}]
  • I understand, i am new bee in python and working on automation and hence looking for help based on my requirement.. I have updated my question. Please let me know if you can help me out here, that will be very much helpful – Shrikant Dec 04 '19 at 13:45
  • let me know if that's what you wanted or not. you now get an array of dicts, that's also the standard json input format, if you're still interested on it. – Enrico Belvisi Dec 04 '19 at 14:28
  • if you want (in this specific case) 2 dictionaries, you can simply extract each of them from the array in 2 variables via a for loop. that's trivial, but maybe the reason you are saying you want an output of type dict instead of an array – Enrico Belvisi Dec 04 '19 at 14:41
  • That worked perfectly, Can you please explain me below two lines, that would really help me to understand more in depth idx_list = [idx + 1 for idx, val in enumerate(store) if 'actual_size ' in val] #note the blank space!!!! storeNew = [dict(store[i: j]) for i, j in zip([0] + idx_list, idx_list + ([size] if idx_list[-1] != size else []))] – Shrikant Dec 04 '19 at 15:14
  • `storeNew` is a list which contains 2 dictionaries. – Marios Nikolaou Dec 04 '19 at 15:58
  • `idx_list` create a list which contains the index at which cut the store list (in your case so idx_list=(3,6), which are the index in which is located the 'actual_size' element ). `storeNew` create an array of dicts. Each dict contains 3 element of the store list cause with that zip formula we made the loop look at range 0,3 & 3,6 [hardcoded is `zip( (0,3,6),(3,6,6) )`]. All this was necessary cause if we loop on the entire list, instead, the keys with the same name would be overwritten, leaving with only the last element of your entire list. – Enrico Belvisi Dec 04 '19 at 16:04
0

I have noticed that you have duplicate keys but you cannot add duplicate keys to dictionary, so you have to iterate the 2 sub lists and create 2 dictionaries.Then i have appended the 2 dictionaries in a list of dictionaries.I hope i understand the question.Check my answer.

store=[ ['hostname ','ABCD','fsystem ','/dev/sdb','actual_size ','2.5T'],
        ['hostname ','XYZ','fsystem ','/dev/sdb','actual_size ','2.5T']
      ] 

def convert_to_dictionary(a): 
    it = iter(a) 
    res_dct = dict(zip(it, it)) 
    return res_dct 

dictionaries = []          
#iterate each sublist in store list
for lst in store:
   dictionary = convert_to_dictionary(lst)
   dictionaries.append(dictionary);

for di in dictionaries:
  print(di) 
Marios Nikolaou
  • 1,326
  • 1
  • 13
  • 24