You could just iterate over the indices of the range of the len of your list:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
for key in dataList[index]:
print(dataList[index][key])
or you could use a while loop with an index counter:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
index = 0
while index < len(dataList):
for key in dataList[index]:
print(dataList[index][key])
index += 1
you could even just iterate over the elements in the list directly:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for key in dic:
print(dic[key])
It could be even without any lookups by just iterating over the values of the dictionaries:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for val in dic.values():
print(val)
Or wrap the iterations inside a list-comprehension or a generator and unpack them later:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
print(*[val for dic in dataList for val in dic.values()], sep='\n')
the possibilities are endless. It's a matter of choice what you prefer.
Answer from MSeifert on Stack OverflowYou could just iterate over the indices of the range of the len of your list:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
for key in dataList[index]:
print(dataList[index][key])
or you could use a while loop with an index counter:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
index = 0
while index < len(dataList):
for key in dataList[index]:
print(dataList[index][key])
index += 1
you could even just iterate over the elements in the list directly:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for key in dic:
print(dic[key])
It could be even without any lookups by just iterating over the values of the dictionaries:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for val in dic.values():
print(val)
Or wrap the iterations inside a list-comprehension or a generator and unpack them later:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
print(*[val for dic in dataList for val in dic.values()], sep='\n')
the possibilities are endless. It's a matter of choice what you prefer.
use=[{'id': 29207858, 'isbn': '1632168146', 'isbn13': '9781632168146', 'ratings_count': 0}]
for dic in use:
for val,cal in dic.items():
print(f'{val} is {cal}')
Videos
When you iterate over a list, you get the elements, not the indices. Consider
for car in cars:
for x, y in car["coded"].items():
print(x, y)
i in this iteration is going to be
{
"name": "Ford",
"type": "SHORT",
"coded": {
"1": "Escape",
"2": "Fiesta",
"999": "Gumbo"
}
}
and
{
"name": "Honda",
"type": "SHORT",
"coded": {
"1": "Civic",
"2": "CRV",
"VCR": "Accord"
}
}
and not 1 and 2 as you expected anyways a better way of doing this is going to be
cars= [
{
"name": "Ford",
"type": "SHORT",
"coded": {
"1": "Escape",
"2": "Fiesta",
"999": "Gumbo"
}
},
{
"name": "Honda",
"type": "SHORT",
"coded": {
"1": "Civic",
"2": "CRV",
"VCR": "Accord"
}
}
]
for i in cars:
for x, y in i['coded'].items():
print(x, y)
You could use a generator to only grab ages.
# Get a dictionary
myList = [{'age':x} for x in range(1,10)]
# Enumerate ages
for i, age in enumerate(d['age'] for d in myList):
print i,age
And, yeah, don't use semicolons.
Very simple way, list of dictionary iterate
>>> my_list
[{'age': 0, 'name': 'A'}, {'age': 1, 'name': 'B'}, {'age': 2, 'name': 'C'}, {'age': 3, 'name': 'D'}, {'age': 4, 'name': 'E'}, {'age': 5, 'name': 'F'}]
>>> ages = [li['age'] for li in my_list]
>>> ages
[0, 1, 2, 3, 4, 5]
Hello everyone!
I have been unable to get the values out of a list of dictionaries with python. I've tried many things but nothing that is actually useful.
I have:
my_list = [
{ name: 'alex',
last_name: 'leda'
}
{ name: 'john',
last_name: 'parsons'
}
]I want to be able to loop through all dictionaries of the list and extract both the key and its corresponding value. Any idea as to how I would be able to accomplish this?
Many thanks!
Try r/learnpython for learning the language. This sub is more focused on news according to the sidebar.
my_list = [
{'name': 'alex', 'last_name': 'leda'},
{'name': 'john', 'last_name': 'parsons'}
]
for person in my_list:
for k, v in person.items():
print('{}: {}'.format(k, v))
key is just a variable name.
for key in d:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
For Python 3.x:
for key, value in d.items():
For Python 2.x:
for key, value in d.iteritems():
To test for yourself, change the word key to poop.
In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better.
This is also available in 2.7 as viewitems().
The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).
It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.
In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
for k in dict: ...which is equivalent to, but much faster than
for k in dict.keys(): ...as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
for key in dict.iterkeys(): ... for value in dict.itervalues(): ... for key, value in dict.iteritems(): ...This means that
for x in dictis shorthand forfor x in dict.iterkeys().
In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.
items doesn't work because you are calling it on the list, but you don't need to do that either. As you have the same keys in your dictionaries, just loop over the list and access the dictionary directly:
{% for item in foo %}
{{ item.name }}
{{ item.age }}
{% endfor %}
The documentation on template variables explains how/why the . works when it comes to dictionaries:
Technically, when the template system encounters a dot, it tries the following lookups, in this order:
- Dictionary lookup
- Attribute lookup
- Method call
- List-index lookup
It looks like your loop is iterating over the list, not the dict. You might try a nested loop.
{% for details in data %}
{% for key, value in details.items %}
{{ key }}: {{ value }}
{% endfor %}
{% endfor %}
Since it looks like your dicts have the same keys, you may also do something like:
{% for details in data %}
name: {{ details.name }}
age: {{ details.age }}
{ % endfor %}
If you have larger dicts or dynamic keys, then you're probably better off using nested loops.