Reputation: 39
I'd like to obtain the data of dictionary in the list as follows.
list=[{"length": {"a": 0.05,"b": 0.04}, "id": "66"}]
How should I extract {"a": 0.05,"b": 0.04} and "66" from this list?
Upvotes: 0
Views: 14019
Reputation: 25
You can use pull values from a dict like this too
ls=[{"length": {"a": 0.05,"b": 0.04}, "id": "66"}]
ls[0].values()
dvas = [ds.values() for ds in ls]
dvas = [*map(dict.values, ls)]
you should also try to avoid using built in names(list) for your variable name assignment, you can avoid a lot of bugs with this practice
Upvotes: 0
Reputation:
list=[{"length": {"a": 0.05,"b": 0.04}, "id": "66"}]
for ele in list:
for key, value in ele.items():
print(value)
Output:
{'a': 0.05, 'b': 0.04}
66
Explanation:
As you are using list
, first iterate over the list :
for ele in list:
Then iterate over the dictionary
using .items
:
for key, value in ele.items():
Then print the values:
print(value)
This will be your required output
Upvotes: 0
Reputation: 540
There are multiple problems here:
1) You define a variable named list
, which would clash with the keyword list
. That will lead to confusing results if you later try to create a list
using the keyword.
2) You stored a single dictionary inside of a list. Why not just create a dictionary, like this:
dictionary = {"length": {"a": 0.05,"b": 0.04}, "id": "66"}
And then you could get the data that you want with the following commands:
dictionary["length"] # Gets {"a": 0.05,"b": 0.04}
dictionary["id"] # Gets "66"
However, since you currently have this within a list, the answer to you question is to first get element 0 from the list, and then apply the previous commands. This would look like the following:
list[0]["length"] # Gets {"a": 0.05,"b": 0.04}
list[0]["id"] # Gets "66"
Upvotes: 1