Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #82068

Re: Nested dictionaries from a list ?

Date 2014-12-07 12:01 -0500
From Dave Angel <davea@davea.name>
Subject Re: Nested dictionaries from a list ?
References <72066852-b4a1-4820-b52a-be56f68a0d7b@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.16678.1417971703.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 12/07/2014 11:18 AM, Wacky wrote:
> New to Python, so please go easy.
> I've a list of users, who have different profiles on different computers. How to tackle this through lists and dictionaries? Here is the data example. More interested in learning how to declare this structure and add/delete/extract values from whatever data structure is proposed.
>
> users = [ 'Tom', 'Dick', 'Harry' ]
>
> { 'Tom': { 'computerA: 'Profile101'
>             'computerB: 'Profile102'
>             'computerC: 'Profile103' }
>
> { 'Dick': { 'computerA: 'Profile389'
>              'computerB: 'Profile390' }
>
> { 'Harry': { 'computerA: 'Profile201'
>               'computerB: 'Profile202'
>               'computerC: 'Profile203'
>               'computerD: 'Profile204' }
>
> Thanks in advance
>

I haven't run this through the Python, so please forgive any typos.

Minimal correction, partly to fix missing commas and extra left curlies:

users = [ 'Tom', 'Dick', 'Harry' ]

mess = { 'Tom': { 'computerA: 'Profile101',
            'computerB: 'Profile102',
            'computerC: 'Profile103' },
  'Dick': { 'computerA: 'Profile389',
             'computerB: 'Profile390' },
  'Harry': { 'computerA: 'Profile201',
              'computerB: 'Profile202',
              'computerC: 'Profile203',
              'computerD: 'Profile204' }
}

And now to get a particular profile, you'd do something like:

mess["Tom"]["computerA"]

Or to get the nth user's profile, use

mess[users[n]]["computerC"]

Note that making this tolerant of missing keys is much trickier.

If it were myproblem, I'd not try to use triply nested braces, but make 
a class for the user, which has methods to look up profiles. Chances are 
that you'll soon have other attributes for those users, and you can then 
tack them into the same class.



-- 
DaveA

Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Nested dictionaries from a list ? Wacky <waqar.hafiz@gmail.com> - 2014-12-07 08:18 -0800
  Re: Nested dictionaries from a list ? Dave Angel <davea@davea.name> - 2014-12-07 12:01 -0500
    Re: Nested dictionaries from a list ? Denis McMahon <denismfmcmahon@gmail.com> - 2014-12-07 23:52 +0000
      Re: Nested dictionaries from a list ? Dave Angel <davea@davea.name> - 2014-12-08 08:35 -0500
  Re: Nested dictionaries from a list ? Denis McMahon <denismfmcmahon@gmail.com> - 2014-12-07 23:49 +0000

csiph-web