Question

In: Computer Science

How would I create a nested dictionary given a csv file in Python? Say I want...

How would I create a nested dictionary given a csv file in Python? Say I want to make a dictionary that read

{'country':{'China':'Fit', 'China':'Overweight', 'USA': 'Overweight', 'USA': 'Fit', 'England':'Fit'...}, 'category':{'Asian':'Fit', 'Caucasian': 'Overweight', 'Caucasian':'Overweight', 'Asian': 'Fit', 'Middle Eastern': 'Fit'...}}

given a file that had

country category Weight
China Asian Fit
China Caucasian Overweight
USA Caucasian Overweight
USA Asian Fit
England Middle Eastern Fit...
...

And so on in the file.

Solutions

Expert Solution

# open file

file = open('input.txt', 'r')

data = file.readlines()

# close file

file.close()

# split each line

for i in range(len(data)):

    data[i] = data[i].split()

    temp = ['', data[i][1], '']

    temp[0] = data[i][0]

    for j in range(2, len(data[i])-1):

        temp[1] += ' '+data[i][j]

    temp[2] = data[i][-1]

    data[i] = temp

# create dictionary

required_data = {}

# insert data

required_data[data[0][0]] = {}

required_data[data[0][1]] = {}

for i in range(1, len(data)):

    # insert country

    required_data[data[0][0]][data[i][0]] = data[i][2]

    # insert category

    required_data[data[0][1]][data[i][1]] = data[i][2]

# print

print(required_data)

.

Screenshot:

.

input:

.

Output:

.

Output doesn't match to your output because in dictionary, every index must match to some single value.

but your dictionary has matched multiple values to same index like,

'China':'Fit', 'China':'Overweight'

This can't happen in a dictionary.


Related Solutions

I am trying to create a program that reads from a csv file and finds the...
I am trying to create a program that reads from a csv file and finds the sum of total volume in liters of liquor sold from the csv file by county and print that list out by county in descending order. Currently my program runs and gives me the right answers but it is not in descending order. I tried this:     for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):         index +=1         print("{}. {} {:.2f}".format(county, sums_by_volume[county]))      When I run...
Using python. 1. How to create a dictionary that has an integer as a key and...
Using python. 1. How to create a dictionary that has an integer as a key and a byte as a value? the dictionary keys must contain integers from 0 to 255. It should be similar to UTF-8. When we enter an integer, it should return 1 byte. 2. Create a function when a user gives 1 byte, it should return the key from the previous dictionary.
build a python program that will be performing: - Read a CSV file 'annual.csv' enterprise into...
build a python program that will be performing: - Read a CSV file 'annual.csv' enterprise into a data structure - Count the number of rows and columns - Determine if the data contains empty values - Replace the empty values by 'NA' for strings, '0' for decimals and '0.0' for floats - Transform all Upper case characters to Lower case characters - Transform all Lower case characters to Upper case characters - save back the 'repaired' array as csv -...
Write code to create a Python dictionary called class. Add two entries to the dictionary: Associate...
Write code to create a Python dictionary called class. Add two entries to the dictionary: Associate the key 'class_name' with the value 'MAT123', and associate the key 'sect_num' with '211_145'
Implement a dictionary application using C++ with the following features: Load a dictionary file. Given a...
Implement a dictionary application using C++ with the following features: Load a dictionary file. Given a prefix string that the user specifies, print the first word or all words in the dictionary with that string as their prefix. Given two strings A and B that the user specifies, replace all occurrences of A in the dictionary file with B. Spawning a new editor (e.g., vim) to allow the user to modify the dictionary file. Save the dictionary file afterwards. You...
Implement a dictionary application using C++ with the following features: Load a dictionary file. Given a...
Implement a dictionary application using C++ with the following features: Load a dictionary file. Given a prefix string that the user specifies, print the first word or all words in the dictionary with that string as their prefix. Given two strings A and B that the user specifies, replace all occurrences of A in the dictionary file with B. Spawning a new editor (e.g., vim) to allow the user to modify the dictionary file. Save the dictionary file afterwards. All...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns:...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns: None Description : You want to see what order the items of a particular category in your file would be in if you sorted them by rating. Given a file, a category of clothing, and an order boolean (True for ascending order, False for descending order), create a function that writes a file called “sorted_items.csv” that includes all of the items in the specified...
{PYTHON }You have a CSV file containing the location and population of various cities around the...
{PYTHON }You have a CSV file containing the location and population of various cities around the world. For this question you'll be given a list of cities and return the total population across all those cities. Write a function named "total_population" that takes a string then a list as parameters where the string represents the name of a CSV file containing city data in the format "CountryCode,CityName,Region,Population,Latitude,Longitude" and the second parameter is a list where each element is itself a...
{PYTHON }You have a CSV file containing the location and population of various cities around the...
{PYTHON }You have a CSV file containing the location and population of various cities around the world. For this question you'll be given a list of cities and return the total population across all those cities. Write a function named "total_population" that takes a string then a list as parameters where the string represents the name of a CSV file containing city data in the format "CountryCode,CityName,Region,Population,Latitude,Longitude" and the second parameter is a list where each element is itself a...
*Python* 1.1) Create an empty dictionary called 'addresses'. The dictionary you just created will map names...
*Python* 1.1) Create an empty dictionary called 'addresses'. The dictionary you just created will map names to addresses. A person's name (stored as a string) will be the KEY and that person's address (stored as a string) will be the VALUE. 1.2) Insert into the dictionary 'addresses' the names and addresses of two (possibly imaginary) friends of yours. 1.3) Create a second empty dictionary called 'ages'. The dictionary you just created will map names to ages. A person's name (stored...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT