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

Convert dictionary into "=" seperated string

I am learning python and I am stuck on something.

I am trying to convert list of dictionaries into = seperated list. I have tried many times but it is either showing an error or showing unexpected results.

python_program.py

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

list_of_dictionary = [{"name": "Cool", "id": 0}, {"name": "Good", "id": 1}, {"name": "Bad", "id": 3}]

s = ",".join([str(i) for i in list_of_dictionary])

print(s)
// {"name": "Cool", "id": 0}, {"name": "Good", "id": 1}, {"name": "Bad", "id": 3}
// this is converted as string

// converting the string to dict
d = ast.literal_eval(s)


e = ", ".join(["=".join([key, str(val)]) for key, val in d.items()])

but this is showing

AttributeError: ‘tuple’ object has no attribute ‘items’

I am trying to get it like

0=Cool, 1=Good, 3=Bad

Then I tried

s = ", ".join(["=".join([key, str(val)]) for key, val in list_of_dictionary[0].items()])

print(s)

But is showed

name=Cool, id=0

not

0=Cool

I am not including key in string just values of the dictionary.

>Solution :

Why .items? you are looking for 2 specific keys. Also, using an f-string (or .format for that matter) removes the need to call str(..._).

list_of_dictionary = [
    {"name": "Cool", "id": 0},
    {"name": "Good", "id": 1},
    {"name": "Bad", "id": 3}
]

print(', '.join(f'{d["id"]}={d["name"]}' for d in list_of_dictionary))

outputs

0=Cool, 1=Good, 3=Bad
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