user8276375
user8276375

Reputation: 3

Accessing a dictionary inside a list

I am reading the Python crash course book, and I am stuck on something. I would like to iterate over a dictionary that's in a list to print out the values in the dictionary. I have 3 dictonaries that I put into a list, and Id like to iterate and print out the information from the dictonaries. Is this even possible?

Upvotes: 0

Views: 66

Answers (2)

JohnAD
JohnAD

Reputation: 899

If you are doing a lot of list-of-dictionary manipulation, then there is a dedicated library for this called PLOD. It can be found on PyPI. Example of use:

>>> lod = [{'a': 1, 'b': 2}, {'a': 9, 'c': 3}]
>>> from PLOD import PLOD
>>> print PLOD(lod).returnString()
[
    {a: 1, b:    2, c: None},
    {a: 9, b: None, c:    3}
]
>>> print PLOD(lod).returnString(honorMissing=True)
[
    {a: 1, b: 2      },
    {a: 9,       c: 3}
]

Docs are at https://github.com/MakerReduxCorp/PLOD/wiki.

Unfortunately, the library has not been upgraded to Python3 yet (I'm helping out with that.)

Upvotes: 0

meow
meow

Reputation: 2191

Something like this should do the job, where dic = dictionary:

for your_dic in your_list:
    for key in your_dic:
        print(your_dic[key])

If you want to access just one specific dictionary you could do:

temp_dict = your_list[0] # assign 0th element of the list to temp_dict
# Iterate over all keys in your dictionary and print them
for key in temp_dict:
    print(temp_dict[key])

Keep in mind that dictionaries are not ordered, so iterating over all keys will not always lead to the same order of print statements

Upvotes: 1

Related Questions