Iterating over a list of dictionary with multiple properties

Viewed 63

I have a list of dictionaries with different number of key value pairs like below:

movie= [{'title': 'j', 'yor': 'n', 'dir': 'jn'}, {'title': 'hb', 'yor': 'jn', 'dir': 'kn'}]

I want to print them like below:

title: j, yor: n, dir: jn
title: hb, yor: jn, dir: kn

I tried two different approaches that is to use .items() to iterate over dictionary inside a nested for loop which iterates over the list. But in that, the output is coming out to be on 6 different lines- each item of dictionary on different lines. And, if I try to print out directly the value of list elements(ie. the dictionaries), the output is pretty raw with brackets and apostrophe which is not desired. Any advice on how this could be achieved?

Code of approach 1:

    for _ in movie:
        print(_)

The output is:

{'title': 'j', 'yor': 'n', 'dir': 'jn'}
{'title': 'hb', 'yor': 'jn', 'dir': 'kn'}

Code of approach 2:

    for _ in movie:
        for k,v in _.items():
            print(k+": " +v)

Output of approach 2:

title: j
yor: n
dir: jn
title: hb
yor: jn
dir: kn
1 Answers

You can try the following:

for item in movie:
    print(f"title: {item['title']}, yor: {item['yor']}, dir: {item['dir']}")

Assuming the order of the keys in the list will be the same:

for item in movie:
    print(','.join(f"{key}: {value}" for key, value in item.items()))
Related