0

this is probably a simpler question but I just don't seem to get how to do it. I have a list with strings, e.g.

my_list = ["a_foo", "b_foo"].

And I have a dictionary with keys as strings and my values are lists that contain strings, e.g.

my_dict = {"key_foo": ["a_bar"], "another_foo": ["c_bar", "False"]}.

I tried to write a list comprehension that appends all key-value pairs to my existing list when the list does not contain "False". This is it

my_list.extend([[key, value] for (key, value) in my_dict.items() if 'False' not in value])

I get the output ["a_foo", "b_foo", ["key_foo", ["a_bar"]]]. I absolutely understand why this is happening, however, I have not been able to find a way to make the output look like this instead: ["a_foo", "b_foo", "key_foo", ["a_bar"]]. Could someone please explain how to do it? I would really appreciate it!

NewOasis
  • 63
  • 1
  • 7

2 Answers2

1

Here is a modification of your code to do this:

my_list = ["a_foo", "b_foo"]
my_dict = {"key_foo": ["a_bar"], "another_foo": ["c_bar", "False"]}

[my_list.extend([key, value]) for (key, value) in my_dict.items() if 'False' not in value]

Doing it in multiple lines also work:

my_list = ["a_foo", "b_foo"]
my_dict = {"key_foo": ["a_bar"], "another_foo": ["c_bar", "False"]}

for (key, value) in my_dict.items(): 
    if 'False' not in value:
        my_list.extend([key, value])

When you do it in multiple lines, it is clearer now why your original code did not work. It is because the previous code appends each key-value pair as one element, and what we wanted to achieve was to append the key and the value as two separate elements. Moving the extend method into the inner loop prevents using the key-value pair as one element.

Edit:

This is how to do it in list comprehension by "flatening" the array instead

my_list = ["a_foo", "b_foo"]
my_dict = {"key_foo": ["a_bar"], "another_foo": ["c_bar", "False"]}

my_list.extend([i for pair in my_dict.items() for i in pair if "False" not in pair[1]])
dee cue
  • 983
  • 1
  • 7
  • 23
  • Thank you very much. :) So just to be clear: It could not have worked with a list comprehension either way? – NewOasis Jan 29 '21 at 16:04
  • You can do that by "flatening" the list of lists. See my updated answer. – dee cue Jan 29 '21 at 16:17
  • 1
    First version: please do not use a list comprehension to perform a side effect. See : https://stackoverflow.com/a/5753614/6914441 – jferard Jan 29 '21 at 17:07
1

You were close to the result with list comprehensions. Once you have filtered on values that do not contain 'False', you just have to iterate over the tuple (key, values), that is return the key then the values:

>>> my_list = ["a_foo", "b_foo"]
>>> my_dict = {"key_foo": ["a_bar"], "another_foo": ["c_bar", "False"]}
>>> my_list.extend([e for k, vs in my_dict.items() if 'False' not in vs for e in (k, vs)])
>>> my_list
['a_foo', 'b_foo', 'key_foo', ['a_bar']]
jferard
  • 7,835
  • 2
  • 22
  • 35