-1

With a list comprehension like this, it is possible to extract a specific value from a key in a list of dictionaries:

ke = [d['_text'] for d in ls if '_text' in d]

Is it possible to extract two values at a time and store them as a tuple with one list comprhension?

So something like this:

ke = [(d['_text'] + e['url']) for (d,e) in ls if '_text', 'url' in d,e]

EDIT: Excuse me for not posting an example:

ls =[{'_text': 'hello', 'url': 'xxx-444.html'}, {'_text': 'bye', 'url': 'xxx-222.html'}]

Desire output:

ke = [('hello', 'xxx-444.html'), ('bye', 'xxx-222.html')]
gython
  • 865
  • 4
  • 18

2 Answers2

2

Try this :

>>> ls =[{'_text': 'hello', 'url': 'xxx-444.html'}, {'_text': 'bye', 'url': 'xxx-222.html'}]
>>> ke = [(d.get('_text'), d.get('url')) for d in ls]
>>> ke
[('hello', 'xxx-444.html'), ('bye', 'xxx-222.html')]

It can handle even if '_text' and 'url' keys are not in any dictionary and in those cases NoneType would be added to the tuple. Like for the following case, last dictionary doesn't contain the 'url' key and None is in place of that :

>>> ls =[{'_text': 'hello', 'url': 'xxx-444.html'}, {'_text': 'bye', 'url': 'xxx-222.html'}, {'_text' : 'world'}]
>>> ke = [(d.get('_text'), d.get('url')) for d in ls]
>>> ke
[('hello', 'xxx-444.html'), ('bye', 'xxx-222.html'), ('world', None)]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
  • A follow up question, what if I got a second text field in every dictionary like ```'_text2'```. Could I extract ```_text'``` and ```'_text2'``` with the same statement to join them? Like ```d.get('_text', '_text2')```? – gython Nov 21 '19 at 14:54
  • 1
    @gython No, that `.get()` on dictionary works like `d.get('key_', 'default_val')` i.e. it says look up in the dictionary the value of the key `'key_'` and if can't find then return `'default_value'`. So, you would need `[(d.get('_text', d.get('_text2')), d.get('url')) for d in ls]`. It would check first if `'_text'` key is there, get that value if not found then get the value for the key `'_text2'`. – Arkistarvh Kltzuonstev Nov 21 '19 at 14:57
  • So it's not possible to get ```_text``` and ```_text2``` joined in one statement? Thanks for the clarification. – gython Nov 21 '19 at 15:03
  • 1
    It's not like you can't join them. Try this `[(d.get('_text','')+ d.get('_text2',''), d.get('url')) for d in ls]` with `ls = [{'_text': 'hello'}, {'_text2': 'world'}, {'_text': 'test', '_text2': 'success'}]`. It would give : `[('hello', None), ('world', None), ('testsuccess', None)]`. See how the value for both the key `'_text'` and `'_text2'` are conjoined if present in a single dictionary. – Arkistarvh Kltzuonstev Nov 21 '19 at 15:09
-1

Sure.

ke = [(d['_text'], e['url']) for d in ls for e in ls if '_text' in d and 'url' in e]

Although this should conceptually work, please share a verifiable example.

FatihAkici
  • 4,679
  • 2
  • 31
  • 48