Python Nesting-A list of dictionaries
Nesting-A list of dictionaries
It's sometimes useful to store a set of dictionaries in a list; this is called nesting.
It's sometimes useful to store a set of dictionaries in a list; this is called nesting.
#Storing dictionaries in a list #start with a empty list. users = [] # Make a new user, and add them to the list. new_user = { 'last': 'fermi', 'first': 'enrico', 'username': 'efermi', } users.append(new_user) #Make another new user, and add them as well. new_user = { 'last': 'curie', 'first': 'marie', 'username': 'mcurie', }1 users.append(new_user) # show all information about each user. for user_dict in users: for k, v in user_dict.items(): print(k + ":" + v) print("\n") #You can also define a list of dictionaries directly, without using append(): #Define a list of users, where each user # is represented by adictionary. users = [ { 'last': 'fermi', 'first': 'enrico', 'username': 'efermi', }, { 'last': 'curie', 'first': 'marie', 'username': 'mcurie', }, ] # Show all information about each user. for user_dict in users: for k, v in user_dict.items(): print(k + ":" + v) print("\n")
No comments:
Post a Comment