0

I have list list like this

[[], ['1.0', '1.0 (proxy)', '1.1', '1.1 (proxy)', '2.0', '2.0 (proxy)', '3.0', '3.0 (proxy)'], ['1.0', '1.0 (proxy)', '1.1', '1.1 (proxy)', '2.0', '2.0 (proxy)', '3.0', '3.0 (proxy)'], ['2.0', '2.0 (proxy)']]

I want to convert this list of lists to dict in a way that float values become key and corresponding string to its value, so {'1.0': '1.0 (proxy)' ....}

when I try to izip it comes as iterator but then error when wrapping with dict.

>>> for item in izip(li):
...  print item
... 
([],)
(['1.0', '1.0 (proxy)', '1.1', '1.1 (proxy)', '2.0', '2.0 (proxy)', '3.0', '3.0 (proxy)'],)
(['1.0', '1.0 (proxy)', '1.1', '1.1 (proxy)', '2.0', '2.0 (proxy)', '3.0', '3.0 (proxy)'],)
(['2.0', '2.0 (proxy)'],)
>>> for item in izip(li):
...  if item:
...   print dict(item)
... 
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ValueError: dictionary update sequence element #0 has length 0; 2 is required
Chang Zhao
  • 631
  • 2
  • 8
  • 24
  • 2
    Do you want a single dictionary as output or a list of dictionaries, one for each list item (right now you have for list items in the initial list). – Andre.IDK Sep 11 '20 at 15:12
  • 1
    If you want a single dict, what should happen with duplicate keys with different values? – ekhumoro Sep 11 '20 at 15:14
  • Also, is order of these items in the lists guaranteed? I.e. float always first and string always after its float value? And is the value in the string always the same as its float? I.e. '1.0' always precedes a '1.0 (proxy)'? – Andre.IDK Sep 11 '20 at 15:17

1 Answers1

0

You can create an iterator of each sub-list and step through it two elements at a time. This way you get key-value pairs, and when the iterator is exhausted, you go to the next sub-list. This will also skip empty lists

def create_dicts(lst):
    new_list = []

    for item in lst:
        # create new dict
        d = {}

        # iterator over the sub list
        x = iter(item)
        
        while True:
            try:
                # check if anything is left in the iterator
                key, value = next(x), next(x)
            except StopIteration:
                # if not, leave the while loop
                break
            # set the key and value in the dictionary
            d[key] = value

        # if the dictionary has any elements
        if d:
            new_list.append(d)
        else:
            continue
    return new_list


li = [[], ['1.0', '1.0 (proxy)', '1.1', '1.1 (proxy)', '2.0', '2.0 (proxy)', '3.0', '3.0 (proxy)'], ['1.0', '1.0 (proxy)', '1.1', '1.1 (proxy)', '2.0', '2.0 (proxy)', '3.0', '3.0 (proxy)'], ['2.0', '2.0 (proxy)']]

a = create_dicts(li)
print(a)

[{'2.0': '2.0 (proxy)', '1.0': '1.0 (proxy)', '1.1': '1.1 (proxy)', '3.0': '3.0 (proxy)'}, {'2.0': '2.0 (proxy)', '1.0': '1.0 (proxy)', '1.1': '1.1 (proxy)', '3.0': '3.0 (proxy)'}, {'2.0': '2.0 (proxy)'}]
C.Nivs
  • 12,353
  • 2
  • 19
  • 44