Nested dictionaries from a list ?
Dave Angel
davea at davea.name
Sun Dec 7 12:01:26 EST 2014
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
More information about the Python-list
mailing list