Home > OS >  Convert a list of delimited strings to a dictionary
Convert a list of delimited strings to a dictionary

Time:01-21

I have an input list of the form

c = ['a|b', 'c|d', 'e|f']

which I want to convert to dict like

c_dict = {'b': 'a', 'd': 'c', 'f': 'e'}

I could do this with a comprehension like

c_dict = {el.split('|')[1]: el.split('|')[0] for el in c}

But the repeated el.split looks ugly. Is there a more succinct one-liner to get the desired result?

CodePudding user response:

this should do it for the one-liner case:

print(dict(reversed(i.split('|')) for i in ['a|b', 'c|d', 'e|f']))

CodePudding user response:

The thing here is to split the entries by | and take second value as key and first as value for the dictionary. So basically you can do this:

def list_to_dict(entries):
    res = {}
    for entry in entries:
        item = entry.split('|')
        res[item[1]] = item[0]
    return res

or a shorter version would be:

def list2dict(entries):
    return dict(reversed(x.split('|')) for x in entries)

CodePudding user response:

As dict([[1,2]])={1: 2} we can use this as:

c = ['a|b', 'c|d', 'e|f']
c_dict = dict(t.split("|")[::-1] for t in c)

edited by point of @deceze

  •  Tags:  
  • Related