Nested dictionaries from a list ?
Denis McMahon
denismfmcmahon at gmail.com
Sun Dec 7 18:49:03 EST 2014
On Sun, 07 Dec 2014 08:18:03 -0800, Wacky wrote:
> New to Python, so please go easy.
> I've a list of users, who have different profiles .....
How are you getting on with this assignment / homework?
I have a solution I could post, but I thought I'd wait to see what your
solution was first.
Here's a hint though, I defined the following functions to work on my
profiles data:
def is_user(user):
def is_machine(machine):
def is_user_of_machine(user, machine):
def is_machine_of_user(user, machine):
def query_machines_of_user(user):
def query_machines():
def query_users_of_machine(machine):
def query_users():
def add_profile(user, machine, profile):
def get_profile(user, machine):
def remove_profile(user, machine):
def remove_user(user):
After defining the functions, I was able to add the following code:
add_profile('Tom', 'computerA', 'Profile101')
add_profile('Tom', 'computerB', 'Profile102')
add_profile('Tom', 'computerC', 'Profile103')
add_profile('Dick', 'computerA', 'Profile389')
add_profile('Dick', 'computerB', 'Profile390')
add_profile('Harry', 'computerA', 'Profile201')
add_profile('Harry', 'computerB', 'Profile202')
add_profile('Harry', 'computerC', 'Profile203')
add_profile('Harry', 'computerD', 'Profile204')
print 'The users are:', query_users()
print 'The machines are:', query_machines()
print 'Users of computerC are:', query_users_of_machine('computerC')
print 'Harry\'s profile on computerB is:', get_profile('Harry',
'computerB')
print 'Tom uses the machines:', query_machines_of_user('Tom')
which generated the following output:
The users are: ['Harry', 'Dick', 'Tom']
The machines are: ['computerA', 'computerB', 'computerC', 'computerD']
Users of computerC are: ['Harry', 'Tom']
Harry's profile on computerB is: Profile202
Tom uses the machines: ['computerA', 'computerB', 'computerC']
Then I added functions to return all of a user's machines and profiles,
and all of a machine's users and profiles.
def query_machine_profiles(user):
def query_user_profiles(machine):
So I could add things like:
print 'The user profiles on computerB are:', query_user_profiles
('computerB')
and get the result:
The user profiles on computerB are: {'Tom': 'Profile102', 'Dick':
'Profile390', 'Harry': 'Profile202'}
By the way, my longest function definition used 7 lines of code, these
are all fairly simple functions, and no list comprehensions.
--
Denis McMahon, denismfmcmahon at gmail.com
More information about the Python-list
mailing list