-2

Suppose I have a list of strings in Python:

['Name: volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index: 24', 
 'Name: volume_xx111', 'Index: 3', 'Name: volume_xx11541', 'Index: 4', 
 'Name: Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index: 6']

How to convert them to a list of dictionaries so the final result will be like this:

[
 {'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index': '24'}, 
 {'Name': 'volume_xx111', 'Index': '3'}, 
 {'Name': 'volume_xx11541', 'Index': '4'}, 
 {'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index': '6}
]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • 1
    There are too many ways to approach this problem. The answers would just turn into a straw-poll for which one people liked. The best thing is to do some research on the topic yourself, find two or three, _analyze_ them, determine if they work for you or not, and _try them out_. Come to us when you have a specific question about something you have attempted to do. – Patrick Artner Mar 10 '19 at 12:26

2 Answers2

1

You need to decide, in code, how to group the strings into dictionaries. Perhaps there are always 2 elements each, or there is always a Name entry, or you simply need to create a new dictionary each time a key has been seen before.

If there are always N elements per dictionary, then iterate in chunks of that size:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

results = [
    dict(tuple(map(str.strip, entry.split(': '))) for entry in per_dict)
    for per_dict in chunks(inputlist, 2)
]

Demo:

>>> from pprint import pprint
>>> inputlist = ['Name: volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index: 24', 'Name: volume_xx111', 'Index: 3', 'Name: volume_xx11541', 'Index: 4', 'Name: Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index: 6']
>>> def chunks(l, n):
...     """Yield successive n-sized chunks from l."""
...     for i in range(0, len(l), n):
...         yield l[i:i + n]
...
>>> [
...     dict(tuple(map(str.strip, entry.split(': '))) for entry in per_dict)
...     for per_dict in chunks(inputlist, 2)
... ]
[{'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index': '24'}, {'Name': 'volume_xx111', 'Index': '3'}, {'Name': 'volume_xx11541', 'Index': '4'}, {'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index': '6'}]
>>> pprint(_)
[{'Index': '24', 'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37'},
 {'Index': '3', 'Name': 'volume_xx111'},
 {'Index': '4', 'Name': 'volume_xx11541'},
 {'Index': '6',
  'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10'}]

If seeing a key repeat is the better approach, then start with a list result containing an empty dictionary; you add key-value pairs to result[-1]. Then process your strings one by one, splitting each on the ':' character to create a key and value pair. If the key already is found in the most recent dictionary, start a new empty one:

results = [{}]
for entry in inputlist:
    key, value = map(str.strip, entry.split(':'))  # removing surrounding whitespace
    if key in results[-1]:
        # start a new dictionary
        results.append({})
    results[-1][key] = value

By checking for the key existing, it no longer matters if a Name and Index entry got swapped.

Demo:

>>> results = [{}]
>>> for entry in inputlist:
...     key, value = map(str.strip, entry.split(':'))  # removing surrounding whitespace
...     if key in results[-1]:
...         # start a new dictionary
...         results.append({})
...     results[-1][key] = value
...
>>> pprint(results)
[{'Index': '24', 'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37'},
 {'Index': '3', 'Name': 'volume_xx111'},
 {'Index': '4', 'Name': 'volume_xx11541'},
 {'Index': '6',
  'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10'}]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-1

My solution is the following:

lista = ['Name: volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index: 24', 
         'Name: volume_xx111', 'Index: 3', 
         'Name: volume_xx11541', 'Index: 4', 
         'Name: Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index: 6']
result = []

for n, item in enumerate(lista):
    if n % 2 == 0:
        result.append({'Name': item[item.find(':') + 2:],
                       'Index': lista[n + 1][lista[n + 1].find(':') + 2:]})
print(result)

With this output:

[{'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index': '24'}, {'Name': 'volume_xx111', 'Index': '3'}, {'Name': 'volume_xx11541', 'Index': '4'}, {'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index': '6'}]