BenH
BenH

Reputation: 720

How to convert a single key within a list of dictionaries to a string on the fly

I'm writing a REST API to manage some storage appliances.

I have the following snippet that returns a list of dictionaries. The dictionaries in the list are completely identical in structure and number/types of keys. I want to concatenate a single key from each dictionary into a string:

result.getJSONData()['chassis']  # returns a list of dictionaries

The actual value I want to concatenate is this (here I'm just looping thru the list and printing the key I want to concatenate):

for chassis in result.getJSONData()['chassis']:
    print chassis['name']

Here is where I want to concatenate and use this string (one of my many attempts at doing this):

log.info("  %s: discovered the following chassis: %s" % (self.name, result.getJSONData()['chassis']['name'].join(", ")))

This is a threaded application so I'm trying to make log entries as autonomous as possible, hence why I'm trying to display this all in one log entry.

Upvotes: 0

Views: 39

Answers (1)

tzaman
tzaman

Reputation: 47830

You're looking for a list comprehension (or generator expression in this case):

', '.join(chassis['name'] for chassis in result.getJSONDATA()['chassis'])

Upvotes: 3

Related Questions