ZickyM
ZickyM

Reputation: 29

How to convert a list to dictionary where some keys are missing their values?

I have a list of objects with their counts associated after a semicolon. Trying to convert this list into a dictionary but some keys will be missing their values once converted. Tried using try/except but not sure how to store the value individually into the dictionary.

Example:

t = ['Contact:10', 'Account:20','Campaign:', 'Country:', 'City:']

The Campaign and Country objects would have no values when converting. I would like to either pass or assign a NaN as the dictionary value.

I tried something like this but with no avail.

for objects in t:
    try:
        dictionary = dict(objects.split(":") for objects in t)
    except:
        pass

Any suggestion is appreciated.

Upvotes: 2

Views: 945

Answers (4)

Christian Sloper
Christian Sloper

Reputation: 7510

You do not really need to try/catch:

t = ['Contact:10', 'Account:20','Campaign:', 'Country:', 'City:']
{ a: b for a,b in (i.split(':') for i in t) }

this yields:

{'Account': '20', 'Campaign': '', 'City': '', 'Contact': '10', 'Country': ''}

If you want None instead of empty string:

{ a: b if b else None for a,b in (i.split(':') for i in t) }

Upvotes: 10

blhsing
blhsing

Reputation: 107005

You can use a generator expression with a split of each item and pass the output to the dict constructor:

dict(i.split(':') for i in t)

This returns:

{'Contact': '10', 'Account': '20', 'Campaign': '', 'Country': '', 'City': ''}

If you would like the assign NaN as a default value you can do it with a dict comprehension instead:

{a: b or float('nan') for i in t for a, b in (i.split(':'),)}

This returns:

{'Contact': '10', 'Account': '20', 'Campaign': nan, 'Country': nan, 'City': nan}

Upvotes: 8

munk
munk

Reputation: 13023

If the value is missing, it will be an empty string

>>> 'foo:'.split(':')
['foo', '']

So this leads us to

data = {}
for pair in t:
    key, value = pair.split(':')
    data[key] = int(value) or float('nan')

This could be cleaned up a little with a dictionary comprehension.

import string
pairs = map(string.split, t)
data = {key: int(value) or float('nan') for key, value in pairs}

You could also decline to put those keys in the dictionary like so

data = {}
for pair in t:
    key, value = pair.split(':')
    if value:
        data[key] = int(value) or float('nan')

Upvotes: 1

Prune
Prune

Reputation: 77860

t = ['Contact:10', 'Account:20','Campaign:', 'Country:', 'City:']
d = {}

for obj in t:
    field = obj.split(':') 
    d[field[0]] = field[1] if field[1] else None

print(d)

Output:

{'Country': '', 'City': '', 'Campaign': '', 'Account': '20', 'Contact': '10'}

Upvotes: 0

Related Questions