2
d= {0: {'Name': 'MN', 'volt': 1.0, 'an': 0.0}, 
    1: {'Name': 'LT', 'volt': 1.0, 'an': 5.8},
    2: {'Name': 'CK', 'volt': 1.0, 'an': 2.72}, 
    3: {'Name': 'QL', 'volt': 1.0, 'an': 0.33}}

I am trying to create a matrix from the above nested dictionary that would result in the following output:

[MN 1.0 0.0
 LT 1.0 5.8
 CK 1.0 2.72
 QL 1.0 0.33]

Using .values() function in python would result in the key names as well.

3
  • It is not possible by itself I thinK. You can not mix integer and strings like that. At least here, you have one list of one element. So please correct. Commented Jan 14, 2021 at 2:07
  • 2
    Try: [list(x.values()) for x in d.values()] Commented Jan 14, 2021 at 2:09
  • There is no built-in data structure as matrix in Python. You should probably clarify what you are trying to do. Commented Jan 14, 2021 at 2:11

1 Answer 1

2

I guess you can them in a list like this

>>> d = {0: {'Name': 'MN', 'volt': 1.0, 'an': 0.0}, 
         1: {'Name': 'LT', 'volt': 1.0, 'an': 5.8},
         2: {'Name': 'CK', 'volt': 1.0, 'an': 2.72}, 
         3: {'Name': 'QL', 'volt': 1.0, 'an': 0.33}}
>>> [list(i.values()) for i in d.values()]
[['MN', 1.0, 0.0],
 ['LT', 1.0, 5.8],
 ['CK', 1.0, 2.72],
 ['QL', 1.0, 0.33]]

You iterate over the values of the outer dictionary and then again, extract the values of interior dictionaries via i.values during iteration, store them in a list with list-comprehension.

If you want them flattened in a list

>>> sum([list(i.values()) for i in d.values()], [])
['MN', 1.0, 0.0, 'LT', 1.0, 5.8, 'CK', 1.0, 2.72, 'QL', 1.0, 0.33]
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was looking for. Thank you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.