Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use join method for a list of dictionaries and then add a string for the value

This is a list of dicts:

list1 = [
    {'unique_id': '1qaz2wsx', 'db_id': 10},
    {'unique_id': '2qaz2wsx', 'db_id': 20},
    {'unique_id': '3qaz2wsx', 'db_id': 30},
    {'unique_id': '4qaz2wsx', 'db_id': 40},
]

I’m trying to have like this as expected output:

unique 1qaz2wsx, url http://url.com/10
unique 2qaz2wsx, url http://url.com/20
unique 3qaz2wsx, url http://url.com/30
unique 4qaz2wsx, url http://url.com/40

I googled for this but I couldn’t find any hints up to now to how to do this. I mean I may googled the incorrect words, so I don’t have any codes and attempts.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I have the expected output?

>Solution :

Try this:

list1 = [
    {'unique_id': '1qaz2wsx', 'db_id': 10},
    {'unique_id': '2qaz2wsx', 'db_id': 20},
    {'unique_id': '3qaz2wsx', 'db_id': 30},
    {'unique_id': '4qaz2wsx', 'db_id': 40},
]

output = '\n'.join([f"unique {d['unique_id']}, url http://url.com/{d['db_id']}" for d in list1])

print(output)

OUTPUT:

unique 1qaz2wsx, url http://url.com/10
unique 2qaz2wsx, url http://url.com/20
unique 3qaz2wsx, url http://url.com/30
unique 4qaz2wsx, url http://url.com/40
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading