Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary comprehension with condition

Suppose that I have a dict named data like below:

{
  001: {
    'data': {
      'fruit': 'apple',
      'vegetable': 'spinach'
    },
    'text': 'lorem ipsum',
    'status': 10
  },
  002: {
    .
    .
    .
  }
}

I want to flatten(?) the data key and convert it to this:

{
  001: {
    'fruit': 'apple',
    'vegetable': 'spinach',
    'text': 'lorem ipsum',
    'status': 10
  },
  002: {
    .
    .
    .
  }
}

I am trying to achieve this using dict comprehensions. Below implementation is with for loops:

mydict = {}
for id, values in data.items():
    mydict[id] = {}
    for label, value in values.items():
        if label == 'data':
            for x, y in value.items():
                mydict[id][x] = y
        else:
            mydict[id][label] = value

I tried below comprehension but it gives syntax error:

mydict = {
    id: {x: y} for x, y in value.items() if label == 'data' else {label: value}
    for id, values in data.items() for label, value in values.items()}

Is there a way to achieve this using comprehensions only?

like image 493
bhdrozgn Avatar asked Dec 01 '25 12:12

bhdrozgn


1 Answers

With dict expansions:

mydict = {i:{**v['data'], **{k:u for k, u in v.items() if k != "data"}} for i, v in data.items()}
like image 129
Andrey Sobolev Avatar answered Dec 03 '25 00:12

Andrey Sobolev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!