Gnaneshwar Babu
Gnaneshwar Babu

Reputation: 111

Dictionary keys as single list

I have a dictionary with keys as tuple and string. I want all the keys as a single list.

mydict={('google','yahoo'):['gmail','browsing'],'wix':['website'],('chrome','firefox'):['Browsers']}
KeysAsList=[]
for k in list(mydict.keys()):
    if type(k)==tuple:
        for item in k:
            KeysAsList.append(item)
    else:
        KeysAsList.append(k)`
print(KeysAsList)

output=['google', 'yahoo', 'wix', 'chrome', 'firefox']

I want to achieve the same output using list comprehension. Thanks in advance. :-)

Upvotes: 1

Views: 62

Answers (4)

RoadRunner
RoadRunner

Reputation: 26315

Not really a list comprehension, but you could also use itertools.chain.from_iterable here to do the flattening after you normalise keys to all tuples. To make a singleton tuple we can use (x,).

>>> from itertools import chain
>>> mydict={('google','yahoo'):['gmail','browsing'],'wix':['website'],('chrome','firefox'):['Browsers']}
>>> list(chain.from_iterable(x if isinstance(x, tuple) else (x,) for x in mydict))
['google', 'yahoo', 'wix', 'chrome', 'firefox']

Upvotes: 0

Tristan Nemoz
Tristan Nemoz

Reputation: 2048

Had you only tuples of strings as keys, you could have used:

output = [key for tup in mydict for key in tup]

But because of the 'wix' as a key, you have to test whether the key is a tuple:

output = [key for tup in mydict for key in (tup if isinstance(tup, tuple) else [tup])]

Upvotes: 1

hurlenko
hurlenko

Reputation: 1425

You can use this list comprehension:

KeysAsList=[k for keys in mydict for k in (keys if isinstance(keys, tuple) else [keys])]

Upvotes: 2

blhsing
blhsing

Reputation: 106480

You can convert a key to a one-item list if it is not a tuple:

output = [i for k in mydict for i in (k if isinstance(k, tuple) else [k])]

Upvotes: 3

Related Questions