0

I would like to organize data currently in a spreadsheet (or CSV) using Python dictionaries. Specifically, I want to be able to extract a specific value if given the person's name.

My idea is to have a dictionary for each name in my list. For example,

| name  | email          | phone | address |
|-------|----------------|-------|---------|
| Alex  | alex@site.com  | 111   | APT 1   |
| Ben   | ben@site.com   | 222   | APT 2   |
| Chris | chris@site.com | 333   | APT 3   |

would be coded as

Alex  = {'email':'alex@site.com',  'phone':'111', 'address':'APT 1'}
Ben   = {'email':'ben@site.com',   'phone':'222', 'address':'APT 2'}
Chris = {'email':'chris@site.com', 'phone':'333', 'address':'APT 3'}

where of course I could use a CSV reader and variables in place of the dictionary values. Doing it this way, if I want Alex's email, I could use Alex['email'].

This works great except I'd like to automate this for a long list of names rather than defining each dictionary individually. As far as I know, variables can't be used to name dictionaries. This seems like a pretty common situation and I'd like to know the best way to go about this, dictionaries or otherwise.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Kyle
  • 127
  • 1
  • 9
  • 1
    Why don't you just use a [`csv.DictReader`](https://docs.python.org/2/library/csv.html#csv.DictReader) then build a dictionary of dictionaries `result = {'d['name]: d for d in reader}`? Then Alex's email is `result['Alex']['email']`. – jonrsharpe Oct 27 '15 at 16:24
  • So, you do have a CSV file with these data? If so, you can parse it. If not, well, you'd have to have the data defined _somewhere_. – TigerhawkT3 Oct 27 '15 at 16:26
  • you should use pandas for this. – acushner Oct 27 '15 at 16:30
  • @jonrsharpe I'm looking into `csv.DictReader`, but the basics of nesting dictionaries in the way you mentioned was sufficient to answer my question. Thanks! – Kyle Oct 27 '15 at 17:14
  • Please don't put answers in the question. Also, note that e.g. `for name, email, phone, address in zip(*data):` is neater than iterating over the indexes. – jonrsharpe Oct 27 '15 at 17:16
  • @jonrsharpe I would have [answered my own question](http://stackoverflow.com/help/self-answer), but because the question was marked as a duplicate I was unable to. Is it really best to have no answer than an answer in the question? (Thanks for the tip on `zip`.) – Kyle Oct 27 '15 at 17:43
  • In that case, you can either: 1. Add your answer to the duplicate, if it applies to it; or 2. Edit your question to clarify how it differs from the duplicate (then it may get reopened and you can add your answer). – jonrsharpe Oct 27 '15 at 17:44

0 Answers0