Home > Blockchain >  Converting a list to a dictionary in python
Converting a list to a dictionary in python

Time:11-24

I have a list in Python that I would like to convert into a dictionary. The list is:

l = [('1:', [362.5815, 162.5823]), ('2:', [154.1328, 354.133]), ('3:', [168.9325, 368.9331]), ('4:', [9.9201, 209.9206]), ('5:', [106.4842, 306.4844])]

The dict should have the integers 1,2,3,4,5 as keys and the lists as values. I have tried using

def Convert(l):
    it = iter(l)
    res_dct = dict(zip(it, it))
    return res_dct  

and

def Convert(l):
    res_dct = {l[i]: l[i   1] for i in range(0, len(l), 2)}
    return res_dct

But these don´t work due to list being an unhashable type. How else could I convert this list? Thanks in advance

CodePudding user response:

d = dict()   
for (k, v) in l:
    d[k.strip(':')] = v

Be aware of repeating keys in your list, as only the last list will be kept, if you expect duplicate keys you need to decide on a strategy to handle them differently (e.g. merge them or keep the first assignment instead of the last assignment as implemented here)

EDIT On below comment off dict comprehension and int conversion for keys, this could also be done (not so sure on legibility though)

{int(key.strip(':')):value for (key,value) in l}

CodePudding user response:

def Convert(l):
    res_dct = {l[i]: l[i   1] for i in range(0, len(l), 2)}
    return res_dct

This is almost right. The problem is that l[i] is an entire tuple as the key. Instead, you want the first element of that tuple: l[i][0]. Similarly, the value needs to be l[i][1] to get the second element of each tuple. With this in mind, there is no reason to skip every other element in the list. Putting it all together:

def Convert(l):
    res_dct = {l[i][0]: l[i][1] for i in range(len(l))}
    return res_dct

A more pythonic way is to iterate over the elements of the list directly rather than using indexes on the list:

def Convert(l):
    res_dct = {i[0]: i[1] for i in l}
    return res_dct

And you can use some more python syntax to get rid of indexing the tuple, too:

def Convert(l):
    res_dct = {k: v for k, v in l}
    return res_dct

But the dict() class already does this with a list of pairs, so we can simplify this even more:

def Convert(l):
    res_dct = dict(l)
    return res_dct

All of these three variations will turn the list of tuples into a dictionary. However, they will use the elements exactly as they are. In particular, the key will be a string with digits and then a colon. If you want to modify they keys to be integers, then you can't use the final version that calls dict(). Instead we will use the dictionary comprehension and apply some functions to the key:

def Convert(l):
    res_dct = {int(k.strip(':')): v for k, v in l}
    return res_dct

After all that, I would consider just making a list of lists. When keys are in sequential order, a list makes more sense than a dictionary:

def Convert(l):
    res = [v for k, v in l]
    return res

The keys are taken care of by the list for you. This assumes that the original elements are already in order.

CodePudding user response:

You can use a dictionary comprehension and enumerate

{i: v[1] for i,v in enumerate(l, 1)}
  • Related