The Python Oracle

Return dictionary value as tuple or list from a string

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Question
01:05 Accepted answer (Score 5)
01:46 Answer 2 (Score 0)
02:08 Thank you

--

Full question
https://stackoverflow.com/questions/3821...

Accepted answer links:
[dict-comprehensions]: https://www.python.org/dev/peps/pep-0274/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ACCEPTED ANSWER

Score 5


You can create the dictionary with a nested dictionary-comprehension:

>>> data = """Xyz         pqrs,uvw
... Abc             foo,bar,blub"""
>>> d = {key: values.split(",") for key, values in 
            (line.split() for line in data.splitlines())}
>>> d
{'Xyz': ['pqrs', 'uvw'], 'Abc': ['foo', 'bar', 'blub']}

Then check containment with any:

>>> any("pqrs" in v for v in d.values())
True

Update: Since you seem to be using Python 2.6, before the existence of dict-comprehensions, you'll have to use this equivalent form:

>>> d = dict((key, values.split(",")) for key, values in 
             (line.split() for line in data.splitlines()))



ANSWER 2

Score 0


You have to clarify your rules. But from what you've shown us this regular expression should do the job

import re
pattern = re.compile(r'[\s,]*')
result = {}
for line in data.strip().splitlines():
    parts = pattern.split(line)
    key = parts[0]
    values = parts[1:]
    if 'pqrs' in values:
        print 'yes'
    result[key] = values