I have a dictionary like this which has nested lists:
data =
{
"id": 212,
"primer_apellido": "Apellido1",
"segundo_apellido": "Apellido2",
"primer_nombre": "Nombre1",
"segundo_nombre": "Nombre2",
"genero": "masculino",
"lugar_de_nacimiento": "Lugar Nacimiento",
"facultad": "",
"departamento": "",
"categoria": "P2",
"apellido": "Apellido1 Apellido2",
"nombre": "Nmbre1 Nombre2",
"related": {
"articulos": [
{
"id": 2557
},
{
"id": 2256
},
{
"id": 2312
}
],
"libros": [
{
"id": 535
},
{
"id": 537
},
{
"id": 538
}
],
"proyectos": [],
"grado-academico": [],
"capacitacion": []
}
}
Enter the element related
and take out articulos
as follows:
listaidArticulos = []
for i in data['related']['articulos']:
listaidArticulos.append(i)
print('lista-->>>>>>>>>',listaidArticulos)
Which returns me:
lista-->>>>>>>>> [{'id': 2557}, {'id': 2256}, {'id': 2312}]
My question is, how can I access articles, books, projects, academic degree, training and obtain the values dynamically, that is, I do not have to put for i in data['related']['articulos']:
or for i in data['related']['libros']
indicate which one I want to access. I hope you can help me. Thanks in advance.
Let's be direct :/, the way I am going to present the solution is a recursive function, recursion is not good because the calls accumulate, if there are many you end up having a stackoverflow , just try not to use it with very large data.
In this function we are going to iterate over the values of the dictionary, if its value is another dictionary, then we make a call to the same function, if it is a list, we iterate over its elements (which will be dictionaries) and we call the same function, in otherwise it means that the value is a string or an integer , so we only store the value in a list called
elementos
we tried
Result
If you want to do it without recursion I think you will have to use some module like integemeter or something similar.
Understanding that what you want is to get the values
"id"
found in the elements inside the dictionary"related": {...}
and store them in a list, you could do the following (in the end there is another way to iterate like this but I consider this more reliable):With Result:
But if you're looking for a format of
[{id:algo1},{id:algo2},{id:algo3},...]
(which I don't see the point of repeating"id"
, unless you expect there to be another element besides"id"
):With result:
Final note: In my experience it's not good to have as much "dynamism" as you want with dictionaries because they are supposed to contain identifiable information that was stored for retrieval, not just random data that you store in them (unless that's what you're looking for). ), all these methods depend on the fact that the structure inside
"related"
is not changed abruptly, if this happens it is better to create different methods for each thing you want to remove although it may seem tedious.EDIT: After trying the ways to iterate, I changed the previous code of the first way because it is more direct with what you are looking for (that is
"id"
to say), then I leave the old code that I had left (which also works):There is something I don't quite understand in your code...
Why do you do the following?:
that gives you back
lista-->>>>>>>>> [{'id': 2557}, {'id': 2256}, {'id': 2312}]
If directly with
print('lista-->>>>>>>>>', data['related']['articulos'])
you will return the same. That is,data['related']['articulos']
it is already a list that has the same thing that you are putting inlistaidArticulos
.At first it doesn't seem like you need to store the data in new lists since you already have it stored in
data
(Why duplicate it?), but rather you need to know how to access it. Still if you need to store them in a new list for some reason, put it in the comments. I say this because in your question you talk about 'accessing the data'.Regardless of this, you can get what's inside by
related
iterating through its elements:In this case, it
f
would take as value the keys of the dictionaries, anddata["related"][f]
their value, and this would return:If what you want is a list with the
id's
, which in this case would be the most logical, you can do it like this:Which would return the following: