Answer to Question #257304 in Python for Ae Dion

Question #257304

determine what's wrong in this code. why x is not defined? Show the correct code.


x.field_names = [ "City name", "Area", "Population", "Annual Rainfall"]

list1 = [


["Adelaide", 1295, 1158259, 600.5],


["Brisbane'', 5905, 1857594, 1146, 4],


[ "Darwin", 112, 120900, 1714, 7],


["Hobart", 135, 20556, 619.5],


["Sydney", 2058, 4336374, 1214.8],


["Melbourne", 1566, 3806092, 646.9],


["Perth", 5386, 1554769, 869.4]]


for i in list1:

x.add_row(i)



1
Expert's answer
2021-10-27T07:40:55-0400

ANSWER FOR THE ABOVE QUESTION


x should be defined as a dictionary, and their is no dictionary field called 'field_names'.

The aim of the program is to convert the two list to dictionaries, i.e. the one containing keys, we call it field_names and the list1 containing the values and then we will add the dictionaries to a list to get a list of of dictionaries.


CORRECT CODE FOR THE ABOVE QUESTION.


#This program aims at making a list of dictionary
#We will convert the fieldnames list and list1 to dictionary and add it to our list
#declare the main list
main_list = []
#declare x a dictionary
x = {}
#This becomes the list for dictionary keys
field_names = [ "City name", "Area", "Population", "Annual Rainfall"]

list1 = [
["Adelaide", 1295, 1158259, 600.5],

["Brisbane", 5905, 1857594, 1146.4],

[ "Darwin", 112, 120900, 1714.7],

["Hobart", 135, 20556, 619.5],

["Sydney", 2058, 4336374, 1214.8],

["Melbourne", 1566, 3806092, 646.9],

["Perth", 5386, 1554769, 869.4]]

# to convert lists to dictionary and add it to list
for i in range(0, len(list1)):
    for key in field_names:
        for value in list1[i]:
            x[key] = value
            list1[i].remove(value)
            break
    #Add the dictionary to our list
    main_list.append(x)

    # Printing resultant dictionary
print("Resultant Main list is : " + str(main_list))


SAMPLE PROGRAM OUTPUT






Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS