nasia jaffri
nasia jaffri

Reputation: 823

Function to convert List to Dictionary and viceversa using Python

I am trying to write a function that will convert a dictionary to a list (with dictionary key as the first value in the list) and a list back to a dictionary. For example, given

dict1 = {'a':[1,2], 'b':[3], 'c':[4,5]}, 

the function should return an answer:

[['a', 1, 2], ['c', 4, 5], ['b', 3]].

Alternatively, if the input is

lst1 = [['a', 1, 2], ['c', 4, 5], ['b', 3]], 

then the function should return:

{'a':[1,2], 'b':[3], 'c':[4,5]}

I have written the following code. It is doing what it is supposed to do except for one problem. If the input is a dictionary, it returns

[['a', [1, 2]], ['c', [4, 5]], ['b', [3]]] (a nested list) instead of
[['a', 1, 2], ['c', 4, 5], ['b', 3]].

My Function Code:

def convertDL(value1):
   if type(value1) == dict:
       scoreList = []
       for key, value in value1.items():
           temp = [key, value]
           scoreList.append(temp)
       return scoreList
   if type(value1) == list:
       scoreDict = {}
       i = 0
       for item in value1:
           scoreDict[value1[i][0]] = value1[i][1:]
           i = i +1
       return scoreDict
convertDL(lst1)

Upvotes: 1

Views: 840

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124998

List comprehensions and dict comprehensions do the work for you:

lst1 = [[k] + v for k, v in dct1.iteritems()]

and

dct1 = {v[0]: v[1:] for v in lst1}

or, as a function:

def convertDL(val):
    if isinstance(val, dict):
        return [[k] + v for k, v in val.iteritems()]
    return {v[0]: v[1:] for v in val}

Use .items() instead of .iteritems() if you are using Python 3.

Demo:

>>> def convertDL(val):
...     if isinstance(val, dict):
...         return [[k] + v for k, v in val.iteritems()]
...     return {v[0]: v[1:] for v in val}
... 
>>> convertDL({'a':[1,2], 'b':[3], 'c':[4,5]})
[['a', 1, 2], ['c', 4, 5], ['b', 3]]
>>> convertDL([['a', 1, 2], ['c', 4, 5], ['b', 3]])
{'a': [1, 2], 'c': [4, 5], 'b': [3]}

Upvotes: 2

Related Questions