Amelia N Chu
Amelia N Chu

Reputation: 351

How to create a dictionary from a list with a list of keys only and key-value pairs (Python)?

This is an extension of this question: How to split a string within a list to create key-value pairs in Python

The difference from the above question is the items in my list are not all key-value pairs; some items need to be assigned a value.

I have a list:

list = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']

I would like to create a dictionary:

dict = { 'abc':'ddd', 'ef':1, 'ghj':1, 'jkl':'yui', 'rty':1 }

I was thinking something along the lines of:

a = {}
for item in list:
   if '=' in item: 
     d = item.split('=')
     a.append(d) #I don't I can do this.
   else:
     a[item] = 1 #feel like I'm missing something here.

Upvotes: 5

Views: 3995

Answers (4)

Moon Cheesez
Moon Cheesez

Reputation: 2701

I would be using something similar to the post you linked.

d = dict(s.split('=') for s in a)

If you combine what you can learn from this post -- that is to use lists to create dictionaries -- and from using if/else in Python's list comprehension, you can come up with something like this:

d = dict(s.split("=", maxsplit=1) if "=" in s else [s, 1] for s in l)

What this does is add 1 to the end of the split list if there is no equal sign in it.

Upvotes: 5

saq7
saq7

Reputation: 1818

input_list = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']
output_dict = {}

for item in input_list:
    item_split = item.split('=')
    key = item_split[0]
    value = item_split[1] if len(item_split)>1 else 1
    output_dict[key] = value

a bit more concisely

for item in input_list:
    i_s = item.split('=')
    output_dict[i_s[0]] = i_s[1] if len(i_s)>1 else 1

This has the advantage that it doesn't append an extra element to each list created by splitting the elements of the input_list. Though, list comprehensions can be faster than a for loop

Upvotes: 1

Hai Vu
Hai Vu

Reputation: 40688

Here are the step-by-step approach.

In [50]: mylist = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']

In [51]: [element.split('=') for element in mylist]
Out[51]: [['abc', 'ddd'], ['ef'], ['ghj'], ['jkl', 'yui'], ['rty']]

In [52]: [element.split('=') + [1] for element in mylist]
Out[52]: [['abc', 'ddd', 1], ['ef', 1], ['ghj', 1], ['jkl', 'yui', 1], ['rty', 1]]

In [53]: [(element.split('=') + [1])[:2] for element in mylist]
Out[53]: [['abc', 'ddd'], ['ef', 1], ['ghj', 1], ['jkl', 'yui'], ['rty', 1]]

In [54]: dict((element.split('=') + [1])[:2] for element in mylist)
Out[54]: {'abc': 'ddd', 'ef': 1, 'ghj': 1, 'jkl': 'yui', 'rty': 1}
  • In order to convert your list in line 50 to a dictionary, you will need to convert it to the list in line 53.
  • Line 51. The first step is to split each element in the list by the equal sign. Each element now is transformed into a list of 1- or 2 elements. Notice that some element like 'ef' which does not have equal sign, we will have to fix that
  • Line 52. Next, we append 1 to each sub list. That should take care of the sublists with 1 element, but making some sublist 3 element long
  • Line 53: We normalize all sublist into 2-element ones by taking just the first two element and discard the third one if applicable. This list now is in the correct format to convert into a dictionary
  • Line 54. The last step is to take this list and convert it into a dictionary. Since the dict class can take a generator expression, we can safely remove the square brackets.

With that, here is the snippet:

mylist = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']
mydict = dict((element.split('=') + [1])[:2] for element in mylist)

Upvotes: 1

Fabricator
Fabricator

Reputation: 12772

For each split "pair", you can append [1] and extract the first 2 elements. This way, 1 will be used when there isn't a value:

print dict((s.split('=')+[1])[:2] for s in l)

Upvotes: 13

Related Questions