goldisfine
goldisfine

Reputation: 4850

How to access a value in a list of dictionaries?

I have a dictionary called 'myjson' that contains a list of dictionaries, indexed by the column names of a tab-delimited spreadsheet. Each row of the spreadsheet is a dictionary, with the keys corresponding to the columns of the spreadsheet and the values corresponding to the entries in the particular row.

Simplified ex:

{'name':'Sam', 'DoB': 5/23/2000'}
{'name':'Jon', 'DoB': 5/10/2000'}

I need to access the name "column" or "set of values" (not sure how to refer to them)?

How do I do this? Had a lot of trouble, trying

myjson[0].itervalues() gives me all the values

but myjson[0][name] doesn't work...


ADDING TO THIS:

I'm trying to parse a string containing a name and a degree. I have a long list of these. Some contain no degrees, some contain one, and some contain multiple.

Ex strings:

Sam da Man J.D.
Green Eggs Jr. Ed.M.
Argle Bargle Sr. MA
Cersei Lannister M.A. Ph.D.

As far as I can tell, the degrees come in the following patterns:

x.x.
x.x.x.
x.x.xx.
x.xx.
xx.x.
x.xxx.
two caps (ex: 'MA')

How would I parse this? I have been reading regex and think that .match() might be the way to go, but I don't understand how to have a list of patterns to match.

Thanks!

Upvotes: 1

Views: 105

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

Use 'name' not name, because without quotes python would think you're referring to some variable name.

Use a list comprehension to get all such values:

>>> lis = [{'name':'Sam', 'DoB': '5/23/2000'},{'name':'Jon', 'DoB': '5/10/2000'}]
>>> [x['name'] for x in lis]
['Sam', 'Jon']

Upvotes: 3

Blair
Blair

Reputation: 6693

You have supplied the dictionary with a key of the string 'name', so that is what you need to use to access it. myjson[0]['name'] should give you what you want.

Upvotes: 3

Related Questions