0

Using the following table, I want to create a dictionary with fruits as the keys and the quantity as values

grades = [['Fruit', 'Apples', 'Bananas', 'Coconut'],
        ['Jim', '4', '5', '6'],
        ['Kevin', '7', '8', '10'],
        ['Clayton', '8', '9', '2']]

For Example :

QuantityList['Apples'] == [4,7,8]

I have the following code below but i get a "'list' object is not callable" error.

num=[y[1:] for y in table[1:]]
fruits = table[0][1:]
QuantityList={y[0]: {int(i) for i in num()} for y in fruits}
print(QuantityList)

Can someone provide some direction on how to fix this?

3
  • 1
    Your example is inconsistent. What is grades? Commented Aug 26, 2017 at 3:41
  • @DYZ true, table should have been called "grades" Commented Aug 26, 2017 at 3:43
  • yup yup.my mistake. I'm actually using a larger dataset, and created a sample problem out of this. Commented Aug 26, 2017 at 4:22

3 Answers 3

3

Looks like what you want is:

QuantityList = {y: [int(x[i]) for x in num] for i, y in enumerate(fruits)}
print(QuantityList) # {'Coconut': [6, 10, 2], 'Apples': [4, 7, 8], 'Bananas': [5, 8, 9]}
Sign up to request clarification or add additional context in comments.

Comments

0

For 1-line sport: The map and zip functions are useful in situations like this:

grades = [['Fruit', 'Apples', 'Bananas', 'Coconut'],
         ['Jim', '4', '5', '6'],
         ['Kevin', '7', '8', '10'],
         ['Clayton', '8', '9', '2']]

result = {row[0] : row[1:] for row in list(map(list, zip(*grades)))[1:]}
print(result)

gives you

{'Apples': ['4', '7', '8'], 'Bananas': ['5', '8', '9'], 'Coconut': ['6', '10', '2']}

Comments

0

You are having that error because you wrote num() instead of num in the QuantityList variable assignment line. You defined num as a list but you are trying to call it as a function with the parentheses.

Another solution could be to use zip to group the columns and then build the dict (after skip the first column ('Fruit', 'Jim', 'Kevin', 'Clayton')):

columns = zip(*grades)
next(columns) # To skip ('Fruit', 'Jim', 'Kevin', 'Clayton')
QuantityList = {c[0]: [int(n) for n in c[1:]] for c in columns}
print(QuantityList) # {'Bananas': [5, 8, 9], 'Apples': [4, 7, 8], 'Coconut': [6, 10, 2]}

With zip(*grades) we are passing every row in grades as parameters to zip function and zip groups the values by column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.