1

I have a list of strings like this:

l = ['ABC, Apple, 20021015, 20030102', 'CDE, Graps, 20020506, 20030130']

I want to convert this list to a dictionary like

d = { 'ABC': 'Apple', 'CDE': 'Graps' }

So the key would be the first name in the string and the value would be the second name in the string.

3 Answers 3

5

This works in Python 2:

d = {j[0]:j[1] for j in [i.split(', ') for i in l]}

Output:

{'CDE': 'Graps', 'ABC': 'Apple'}
Sign up to request clarification or add additional context in comments.

Comments

2

You could do it like this:

for index in range(len(l)):
    line = l[index].split(", ")
    d[line[0]] = line[1]

So, you split each entry by commas to get each name and date individually, and then you can add them each to the dict as normal.

Comments

0

Alternative, shorter form:

>>> dict(x.split(', ')[:2] for x in l)
{'ABC': 'Apple', 'CDE': 'Graps'}

This works by passing a sequence of two-element lists to dict() which then initializes the dictionary based on that sequence. The sequence being passed is this:

>>> [x.split(', ')[:2] for x in l]
[['ABC', 'Apple'], ['CDE', 'Graps']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.