-1

I've done some searching, playing and still can't seem to find a solution.

Say I have a list of dictionaries such as:

listofdicts = [
    {'Name': 'Jim', 'Attribute': 'Height', 'Value': '6.3'},
    {'Name': 'Jim', 'Attribute': 'Weight', 'Value': '170'},
    {'Name': 'Mary', 'Attribute': 'Height', 'Value': '5.5'},
    {'Name': 'Mary', 'Attribute': 'Weight', 'Value': '140'}
]

But I want to place each of those in a singular named dictionary, such as:

listofdicts = [
    {'Person': {'Name': 'Jim', 'Attribute': 'Height', 'Value': '6.3'}},
    {'Person': {'Name': 'Jim', 'Attribute': 'Weight', 'Value': '170'}},
    {'Person': {'Name': 'Mary', 'Attribute': 'Height', 'Value': '5.5'}},
    {'Person': {'Name': 'Mary', 'Attribute': 'Weight', 'Value': '140'}}
]

How would I go about doing that?

I've managed the following, but it only seems to nest one dictionary:

betterlist = { 'Person' : i for i in listofdicts}

Any help would be appreciated. Thank you everyone.

ojdo
  • 8,280
  • 5
  • 37
  • 60
h2co32
  • 21
  • 3

3 Answers3

2

You're close, you're creating a list comprehension, not a dictionary comprehension

betterlist = [{ 'Person' : i} for i in listofdicts]

The reason "it only seems to nest one dictionary" is your dictionary comprehension is using the same key for every element, thus it overwrites previous values with the latest value for i

Sayse
  • 42,633
  • 14
  • 77
  • 146
2

You almost got it right, but your outermost structure should be a list [], while each element you construct is the dictionary {'Person': i} you created:

better_list = [
    {'Person': p}
    for p in list_of_dicts
]

What you wrote is called dict comprehension and only creates a single dictionary. As the keys in a dictionary only can occur once, each iteration i overwrites the single key 'Person', so you end up with the person that happens to be last in your listofdicts.

ojdo
  • 8,280
  • 5
  • 37
  • 60
2

So basically there's 2 (easy) way to do this.

The clearest way is to create a loop:

newDict = []
for d in listofdicts:
    newDict.append({'Person': d}) # I'm creating the dict, and then appending to newDict

There's a shortcut to do the above, called list comprehension.

newDict = [{'Person': d} for d in listofdicts] # Can you compare the 2 approach's syntax?

Understand that this is simply a shortcut. There's no performance improvement whatsoever. If I am new to Python, I would choose the first approach since it is extremely clear for me what it is doing.

  • 1
    Yes, there is a [performance improvement](https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops). – Sayse Apr 06 '21 at 13:26
  • Thank you for the assistance! – h2co32 Apr 06 '21 at 14:13