al3x609
al3x609

Reputation: 181

How to get a list from dict with lambda/maps?

I have this dict, where I manage a list of programs and their different versions

data = {
  'soft1':{
     'v1':{...},
     'v2':{...}
   },
  'soft2':{
     'v1':{...},
     'v2':{...}
  },
  'soft3':{
     'v1':{...}
  },
  ...
}

now I need a list like to:

list_=[
    'soft1 v1',
    'soft1 v2',
    'soft2 v1',
    'soft2 v2',
    'soft3 v1' 
]

with list comprehension

list_ = [soft + " " + ver for soft in data.keys() for ver in data[soft].keys()]

but I would like a more efficient method and more pythonic,

I try:

list_ = [map(lambda soft: map(lambda ver: [soft + " " + ver], data[soft].keys()), data.keys())]

but it generates this error

TypeError: can only concatenate str (not "map") to str

I appreciate opinions and corrections

Upvotes: 1

Views: 222

Answers (1)

jpp
jpp

Reputation: 164693

You can use a list comprehension with f-strings (available in Python 3.6+):

res = [f'{k} {w}' for k, v in data.items() for w in v]

['soft1 v1', 'soft1 v2', 'soft2 v1', 'soft2 v2', 'soft3 v1']

For earlier versions of Python you can use str.format:

res = ['{0} {1}'.format(k, w) for k, v in data.items() for w in v]

This will be more efficient as:

  • Formatted string literals are more efficient than other methods of string concatenation.
  • Extracting key-value pairs via dict.items is more efficient than iterating keys and accessing values separately.
  • map + lambda with non built-in functions are less efficient than list comprehensions.

Upvotes: 6

Related Questions