race, football, badminton
yellow, 10, 20
white, 50, 30
red, 80, 100
I have a data similar as above (which is more complex). I wish form the key value pair where the result is as below:
'yellow': {'football': 10, 'badminton': 20}, 'white': {'football': 50, 'badminton': 30}, 'red':{'football': 80, 'badminton': 100}
which the number is in integer instead of string and I can call the value when I search for the key to plot in bar or pie.
first try:
country_activity_time = []
file = open('time-used', 'r')
for data in file:
data = data.rstrip('\n').split(',')
if data[0] != 'Country':
country = data[0]
time_spend = data[1:]
country_time = {country: time_spend}
country_activity_time.append(country_time)
print(country_activity_time)
first outcome:
[{'Australia': ['6', '45', '89', '27', '132', '76', '58', '211', '56', '40', '29', '512', '19', '140']}, {'Austria': ['9', '34', '79', '27', '125', '59', .............etc
the value is not integer and unable to search the data by country nam#
second try:
country_activity_time = []
catogory_all = []
country_all = []
time_spend_all = []
file = open('time-used', 'r')
for data in file:
data = data.rstrip('\n').split(',')
if data[0] == 'Country':
catogory = data[1:]
catogory_all.append(catogory)
else:
country = data[0]
country_all.append(country)
for time_spend in data[1:]:
time_spend = int(time_spend)
time_spend_all.append(time_spend)
print(catogory_all)
print(country_all)
print(time_spend_all)
second outcome:
[['Attending events', 'Care for household members', 'Eating and drinking', 'Education', 'Housework', 'Other leisure activities',.........etc
['Australia', 'Austria', 'Belgium', 'Canada', 'China', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'India', '.............etc
[6, 45, 89, 27, 132, 76, 58, 211, 56, 40, 29, 512, 19, 140, 9, 34, 79, 27, 125, 59, 32, 280, 55, 82, 21, 498, 32, 109, 15, 22, 99, 41, 121,..............etc
the second out come sucessful separate all the key and value but not sure why the category is in that forms (where len(catogory) = 1 and the value not group accordingly
third try:
country_activity_time = []
file = open('time-used', 'r')
for data in file:
data = data.rstrip('\n').split(',')
if data[0] != 'Country':
country = data[0]
for time_spend in data[1:]:
time_spend = int(time_spend)
country_time = {country: time_spend}
country_activity_time.append(country_time)
print(country_activity_time)
third outcome:
[{'Australia': 6}, {'Australia': 45}, {'Australia': 89}, {'Australia': 27}, {'Australia': 132}, {'Australia': 76},.............etc
successful link the country and value bout not the category and also the value separate like that