1

I know it's possible to traverse a dictionary by using iteritems() or keys(). But what if I got a list of dics such as: l = [{'a': 1}, {'b': 2}, {'c': 3}] and I want to compose a string using its keys, e.g., s = 'a, b, c'?

One solution is to copy all the keys into a list in advance, and compose the string I want. Just wondering if there is a better solution.

5
  • @GregS: That's not what this question is about. Commented Feb 11, 2012 at 16:29
  • @GregS It's a list of dictionaries, not a dictionary contains multiple items Commented Feb 11, 2012 at 16:29
  • @NiklasB. How can you be so sure? The description says list of dics but the example is a single dict. Commented Feb 11, 2012 at 16:43
  • @GregS: It's absolutely NOT a single dict (but I have to admit that I also only saw that on second glance :) Commented Feb 11, 2012 at 16:44
  • @NiklasB. <sheepish> .. you're right! It took me 4 glances. Commented Feb 11, 2012 at 16:46

4 Answers 4

8

You can use itertools.chain() for it and make use of the fact that iterating over a dict will yield its keys.

import itertools
lst = [{'a': 1}, {'b': 2}, {'c': 3}] 
print ', '.join(itertools.chain(*lst))

This also works it there are dicts with more than one element.

If you do not want duplicate elements, use a set:

print ', '.join(set(itertools.chain(*lst)))
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming each dictionary will only have a single key:

', '.join(a.keys()[0] for a in l)

if not, maybe something like:

>>> l = [{'a': 1, 'd': 4}, {'b': 2}, {'c': 3}]
>>> ', '.join(', '.join(a.keys()) for a in l)
'a, d, b, c'

Comments

0

Iterate over the dictionaries and then over the keys of each dictionary:

>>> lst = [{'a': 1}, {'b': 2}, {'c': 3}]
>>> ', '.join(key for dct in lst for key in dct.keys())
'a, b, c'

Comments

0

Try this:

 ''.join([i.keys()[0] for i in l])

You can put any delimiter you want inside of the quotes. Just bear in mind that the dictionary isn't ordered, so you may get weird looking strings as a result of this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.