The Python Oracle

Return dictionary value as tuple or list from a string

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Return Dictionary Value As Tuple Or List From A String
00:39 Accepted Answer Score 5
01:11 Answer 2 Score 0
01:18 Thank you

--

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

--

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