Python access dictionary inside list of a dictionary
At the moment you have 3 dictionaries inside a list inside a dictionary. Try the below instead:
my_nested_dictionary = {'mydict': {'A': 'Letter A', 'B': 'Letter C', 'C': 'Letter C'}}
print(my_nested_dictionary['mydict']['A'])
Getting a list of values from a list of dicts
Assuming every dict has a value
key, you can write (assuming your list is named l
)
[d['value'] for d in l]
If value
might be missing, you can use
[d['value'] for d in l if 'value' in d]
Access nested dictionary items via a list of keys?
Use reduce()
to traverse the dictionary:
from functools import reduce # forward compatibility for Python 3
import operator
def getFromDict(dataDict, mapList):
return reduce(operator.getitem, mapList, dataDict)
and reuse getFromDict
to find the location to store the value for setInDict()
:
def setInDict(dataDict, mapList, value):
getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value
All but the last element in mapList
is needed to find the 'parent' dictionary to add the value to, then use the last element to set the value to the right key.
Demo:
>>> getFromDict(dataDict, ["a", "r"])
1
>>> getFromDict(dataDict, ["b", "v", "y"])
2
>>> setInDict(dataDict, ["b", "v", "w"], 4)
>>> import pprint
>>> pprint.pprint(dataDict)
{'a': {'r': 1, 's': 2, 't': 3},
'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}
Note that the Python PEP8 style guide prescribes snake_case names for functions. The above works equally well for lists or a mix of dictionaries and lists, so the names should really be get_by_path()
and set_by_path()
:
from functools import reduce # forward compatibility for Python 3
import operator
def get_by_path(root, items):
"""Access a nested object in root by item sequence."""
return reduce(operator.getitem, items, root)
def set_by_path(root, items, value):
"""Set a value in a nested object in root by item sequence."""
get_by_path(root, items[:-1])[items[-1]] = value
And for completion's sake, a function to delete a key:
def del_by_path(root, items):
"""Delete a key-value in a nested object in root by item sequence."""
del get_by_path(root, items[:-1])[items[-1]]
Get Key from a Value (Where value is in a list)
You could try this:
>>> def corresponding_key(val, dictionary):
for k, v in dictionary.items():
if val in v:
return k
>>> corresponding_key("A", my_dict)
'0'
>>> corresponding_key("B", my_dict)
'0'
>>> corresponding_key("C", my_dict)
'0'
>>> corresponding_key("D", my_dict)
'1'
>>> corresponding_key("E", my_dict)
'1'
>>> corresponding_key("F", my_dict)
'1'
>>>
However, in the case where a value is in multiple dictionary value lists, you can modify the function:
>>> def corresponding_keys(val, dictionary):
keys = []
for k, v in dictionary.items():
if val in v:
keys.append(k)
return keys
Or, you could use list comprehension:
>>> val = "A"
>>> dictionary = my_dict
>>> [k for k, v in dictionary.items() if val in v]
['0']
how to access elements of a list present as a value in key-value pair in a map ,where map is present in another list in Dart
(You should pay attention to the error message you get. If you don't understand the error message, you at least should mention what error you get so that others can help you more easily and so that other people can find your question more easily when searching.)
questions[0]['answers'][0]
doesn't work, failing with: Error: The operator '[]' isn't defined for the class 'Object'.
That provides a hint what's wrong: a type is being inferred as Object
instead of as a more specific type, and then you try to use operator []
on it.
And indeed, your Map
s have heterogeneous values: questiontext
maps to a String
, but answers
maps to a List<String>
. Your Map
s therefore are inferred to be of type Map<String, Object>
since Object
is the common base class of String
and List<String>
.
Ways to fix your code:
Explicitly use
dynamic
to disable static type-checking:var questions = <Map<String, dynamic>>[...];
Explicitly cast when doing lookups:
print((questions[0]['answers'] as List<String>)[0]); // Prints: Black
Use a class instead of a
Map
, which is more appropriate since you have different types for different fields:class QuestionAndAnswers {
QuestionAndAnswers(this.questionText, this.answers);
String questionText;
List<String> answers;
}
var questions = [
QuestionAndAnswers(
'What\'s your favourite color?',
['Black', 'Red', 'Green', 'White'],
),
...
];
print(questions[0].answers[0]); // Prints: Black
Related Topics
Substitute Multiple Whitespace with Single Whitespace in Python
Why Might Python's 'From' Form of an Import Statement Bind a Module Name
Class Inheritance in Python 3.7 Dataclasses
Python Datetime to String Without Microsecond Component
How to Use a Conditional Expression (Expression with If and Else) in a List Comprehension
Overloaded Functions in Python
Scraping Ajax Pages Using Python
Pythonic Way to Create Union of All Values Contained in Multiple Lists
Flask-Sqlalchemy Import/Context Issue
How to Escape Curly-Brackets in F-Strings
Datetime Timezone Conversion Using Pytz
How Could I Use Batch Normalization in Tensorflow
Solving Embarassingly Parallel Problems Using Python Multiprocessing