maudev
maudev

Reputation: 1101

How to concatenate list of dictionaries items using join and list comprehension?

i'm trying to get a formatted string with all attributes from all dictionaries in a list using list comprehension

results = [{'TTL': '1643410114', 'customer': '1212', 'date': '2021-01-28', 'file': 'file.gz'}]

print("***** SEARCH RESULTS ***** \n".join([ f"{key}: {value}\n" for key, value in obj.items() for obj in results ]))

and I got NameError: name 'obj' is not defined, I tried some combinations without success, how can I archieve this?

Upvotes: 0

Views: 109

Answers (4)

results = [{'TTL': '1643410114', 'customer': '1212', 'date': '2021-01-28', 'file': 'file.gz'},
      {'TTL': '1643410115', 'customer': '1312', 'date': '2021-02-27', 'file': 'file2.gz'}
      ]

#print(results)
for obj in results: 
     for key, value in obj.items():
        if (key=='file'):
             print(obj['TTL'],key,value)


output
1643410114 file file.gz
1643410115 file file2.gz

Upvotes: 0

Lumber Jack
Lumber Jack

Reputation: 622

Here is a path to do it...

print("***** SEARCH RESULTS *****")
print(str([k +' : '+ results[0][k] for k in results[0]]).replace('[','').replace(']','').replace(',','\n').replace("'",""))

Upvotes: 1

etudiant
etudiant

Reputation: 121

You need to switch the order of the two for loops.

results = [{'TTL': '1643410114', 'customer': '1212', 'date': '2021-01-28', 'file': 'file.gz'}]

print("***** SEARCH RESULTS ***** \n".join([ f"{key}: {value}\n" for obj in results for key, value in obj.items()]))

Output

TTL: 1643410114
***** SEARCH RESULTS ***** 
customer: 1212
***** SEARCH RESULTS ***** 
date: 2021-01-28
***** SEARCH RESULTS ***** 
file: file.gz

Upvotes: 2

dhuang
dhuang

Reputation: 921

You have your inline for-loops in the wrong order:

>>> [ "{}: {}\n".format(key, value) for obj in results for key, value in obj.items() ]
['customer: 1212\n', 'date: 2021-01-28\n', 'file: file.gz\n', 'TTL: 1643410114\n']

Upvotes: 3

Related Questions