[[python_wiki:list_of_dictionaries_with_a_list_inside]]

List Of Dictionaries With A List Inside

General Information

Code snippet showing a concept in which there is a list of dictionaries. Inside the dictionary, one of the values of a key is a list.

This could come in handy to store a list of groups.

  • Each group in the list would contain a dictionary, with key/value pairs that would represent the group name and member list.
  • The member list would then need to be a list of all users in the group.

The Code

#!/usr/bin/python
 
# Create empty group list
group_list = []
 
# Create empty member list to be used in the group_list dictionary
member_list = []
 
# Add a new dictionary with the group names and member list to the group_list
group_list.append( {'group_name': 'Rebels', 'members': member_list})
 
# Re-initialize the member_list, and create the 2nd dictionary in the group_list
member_list = []
group_list.append( {'group_name': 'Empire', 'members': member_list})
 
# Display the entire group_list
print "The group list is: ", group_list
 
# Show the group_name at group_list position 0
print "The group name at position 0 is: ", group_list[0]['group_name']
print "The group name at position 1 is: ", group_list[1]['group_name']
 
# Append a new member to the members at group_list position 0
group_list[0]['members'].append('yoda')
group_list[0]['members'].append('luke')
 
# Append a new member to the members at group_list position 1
group_list[1]['members'].append('vader')
group_list[1]['members'].append('maul')
 
# Show the members at group_list position 0
print "The members at group 0 is: ", group_list[0]['members']
print "The members at group 1 is: ", group_list[1]['members']

  • python_wiki/list_of_dictionaries_with_a_list_inside.txt
  • Last modified: 2019/05/26 03:50
  • (external edit)