Mortz
Mortz

Reputation: 4939

Convert a list of delimited strings to a dictionary

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?

Upvotes: 1

Views: 1018

Answers (3)

S4eed3sm
S4eed3sm

Reputation: 1478

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

Upvotes: 2

pouya_ghahari
pouya_ghahari

Reputation: 58

this should do it for the one-liner case:

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

Upvotes: 3

Michael
Michael

Reputation: 737

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)

Upvotes: 1

Related Questions