Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to remove the top level key from a nested dictionary and keep the values?

Example of the nested dictionary with the keys to be removed.

{1: {'Email': '[email protected]',
     'FirstName': 'John',
     'Id': {'Value': 1},
     'LastName': 'Doe',
     'UserName': 'JohnDoe'},
 2: {'Email': '[email protected]',
     'FirstName': 'Jane',
     'Id': {'Value': 2},
     'LastName': 'Doe',
     'UserName': 'JaneDoe'},
 3: {'Email': '[email protected]',
     'FirstName': 'Fred',
     'Id': {'Value': 1},
     'LastName': 'Doe',
     'UserName': 'FredDoe'}}

Is it possible to remove the numeric keys and save the dictionary like below?

   {{'Email': '[email protected]',
     'FirstName': 'John',
     'Id': {'Value': 1},
     'LastName': 'Doe',
     'UserName': 'JohnDoe'},
    {'Email': '[email protected]',
     'FirstName': 'Jane',
     'Id': {'Value': 2},
     'LastName': 'Doe',
     'UserName': 'JaneDoe'},
    {'Email': '[email protected]',
     'FirstName': 'Fred',
     'Id': {'Value': 1},
     'LastName': 'Doe',
     'UserName': 'FredDoe'}}
like image 459
Rick C Avatar asked Oct 25 '25 23:10

Rick C


1 Answers

Assuming the dictionary is in a variable d, all you have to do is d.values(), which will give you the values of each of the key, value pairs from the dictionary:

>>> d = {1: {'Email': '[email protected]', 'FirstName': 'John', 'Id': {'Value': 1}, 'LastName': 'Doe', 'UserName': 'JohnDoe'}, 2: {'Email': '[email protected]', 'FirstName': 'Jane', 'Id': {'Value': 2}, 'LastName': 'Doe', 'UserName': 'JaneDoe'}, 3: {'Email': '[email protected]', 'FirstName': 'Fred', 'Id': {'Value': 1}, 'LastName': 'Doe', 'UserName': 'FredDoe'}}
>>> l = list(d.values())
>>> l
[{'Email': '[email protected]', 'FirstName': 'John', 'Id': {'Value': 1}, 'LastName': 'Doe', 'UserName': 'JohnDoe'}, {'Email': '[email protected]', 'FirstName': 'Jane', 'Id': {'Value': 2}, 'LastName': 'Doe', 'UserName': 'JaneDoe'}, {'Email': '[email protected]', 'FirstName': 'Fred', 'Id': {'Value': 1}, 'LastName': 'Doe', 'UserName': 'FredDoe'}]
like image 98
Sean Breckenridge Avatar answered Oct 28 '25 04:10

Sean Breckenridge



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!