galeej
galeej

Reputation: 563

How to use a dict comprehension to split a list?

I currently have a dict in the form:

data = {"var1":"600103", "var2":[{"a":"1","b":"2"}]}

I would like the output to be:

op = {"var1":"600103","var2[0]":{"a":"1","b":"2"}}

I am currently using loops to manually loop through. I'd like to know if there's a more pythonic way of doing this.

Upvotes: 0

Views: 189

Answers (2)

aabilio
aabilio

Reputation: 1727

I do not know if it is very pythonic or not but I know for sure that it is difficult to read :S Sorry, just playing... ;)

data = {"var1":"600103", "var2":[{"a":"1","b":"2"},{"a":"3","b":"4"},{"a":"5","b":"6"},{"a":"7","b":"8"}], "var3":"600103"}
reduce(
    lambda a, b: dict(a.items() + b.items()),
    [
        dict(map(lambda (idx, i): ('{0}[{1}]'.format(key, idx), i), enumerate(value))) if type(value) is list else {key: value} 
        for key, value 
        in data.items()
    ]
)

output:

{'var1': '600103',
 'var2[0]': {'a': '1', 'b': '2'},
 'var2[1]': {'a': '3', 'b': '4'},
 'var2[2]': {'a': '5', 'b': '6'},
 'var2[3]': {'a': '7', 'b': '8'},
 'var3': '600103'}

Upvotes: 1

cs95
cs95

Reputation: 402543

If this isn't what you're already doing, you can eliminate the need for a nested loop by using a dict comprehension for the values which are lists.

data = {"var1":"600103", "var2":[{"a":"1","b":"2"}, {"a":"22","b":"555"}]}

op = {}
for k in data:
    if not isinstance(data[k], list): 
        op[k] = data[k]
    else:
        op.update({k + '[{}]'.format(i) : data[k][i] for i in range(len(data[k])) })

And, your output will look like this:

{'var1': '600103', 'var2[1]': {'a': '22', 'b': '555'}, 'var2[0]': {'a': '1', 'b': '2'}}

Upvotes: 1

Related Questions