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
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.
CodePudding user response:
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
CodePudding user response:
Try this:
', '.join(['='.join([str(v['id']), v['name']]) for v in list_of_dictionary])