Jim
Jim

Reputation: 11

Creating a dictionary from a passed in string

I have a variable foo = "'totalteams': 10, 'totalrounds': 11"

Why can't I do this?

data=dict(foo)

so I can do

print data['totalteams']

I need to use python 2.5 because of google. How do I do what I want?

thanks

Upvotes: 0

Views: 201

Answers (4)

pyInTheSky
pyInTheSky

Reputation: 1469

It's probably not as robust, but it's 2.5 compatible:

import re
foo = "'totalteams':10,'totalrounds':11"
m = re.compile("'(\w+)':(\d+)")
t = m.findall(foo)

you will then get a list of tuples which you can decompose and zip into a dictionary

>>> a,b = zip(*t)
>>> a
('totalteams', 'totalrounds')
>>> b
('10', '11')
>>> d = dict(zip(list(a),list(b)))
>>> d
{'totalteams': '10', 'totalrounds': '11'}
>>> 

credit to http://selinap.com/2009/02/unzip-a-python-list/ :: never knew you could unzip a list : )

Upvotes: 0

Seth Carnegie
Seth Carnegie

Reputation: 75130

Because a string is not a dictionary. You have a couple of options:

Make a dictionary literal:

data = {'totalteams': 10, 'totalrounds': 11}
print data['totalteams']

Have a JSON string or something similar as your data if you have to work with strings:

# as F.J pointed out, json isn't a built-in in python 2.5 so you'll have to get simplejson or some other json library
import json
foo = '{"totalteams": 10, "totalrounds": 11}'
data = json.loads(foo)
print data['totalteams']

# or
foo = '"totalteams": 10, "totalrounds": 11'
data = json.loads('{%s}' % foo)

Or use eval like dminer's answer, but eval should be a last resort.

Upvotes: 1

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

you want to use ast.literal_eval. example:

>>> foo = "'totalteams': 10, 'totalrounds': 11"
>>> import ast
>>> ast.literal_eval("{%s}" % foo)
{'totalteams': 10, 'totalrounds': 11}
>>> 

Edit: Hmm.. on ? You might want to consider using a format that is more easily parsed in that environment. PyYAML is standard there, you might consider using that format instead:

>>> import yaml
>>> yaml.load("""
... totalteams: 10
... totalrounds: 11
... """)
{'totalteams': 10, 'totalrounds': 11}
>>> 

Upvotes: 0

dminer
dminer

Reputation: 1141

foo = "'totalteams': 10, 'totalrounds': 11"
data = eval("{%s}" % foo)
print data['totalteams']

Upvotes: 1

Related Questions