Combining dictionary values with list | SoloLearn: Learn to code for FREE!

+1

Combining dictionary values with list

Hey, I have a task which I need help with. I'm not very good at describing so I will simplify an example: Strawberry is number one, Banana is number two and Apple is number three. Number one shouldn't be eaten with three, number two shouldn't be eaten with one and number three shouldn't be eaten with two. My task now is to write a program that will show the output like this: "Strawberry shouldn't be eaten with Apple" etc. This is what I did until now: fruits = {'1': 'Strawberry', '2': 'Banana', '3': 'Apple'} not_eaten = [3, 1, 2] How can I combine my list with the dictionary so that my numbers from 'not_eaten' will show the corresponding values from the dictionary? In this example my list would look like ['Apple', 'Strawberry', 'Banana']. My real task is much longer and doing this manually by looking each one up is not an option. I'm sorry if this is badly explained and thank you in advance!

6/1/2020 9:29:52 AM

🌱La🐛🌿

3 Answers

New Answer

+7

I think you could use one dictionary, like this: fruits = {1: ('Strawberry', 3), 2: ('Banana', 1), 3: ('Apple', 2)} Then you can address it like: fruits[1][0] ==> 'Strawberry' fruits[1][1] ==> 3 So: fruits[i][0] cannot be eaten with fruits[fruits[i][1]][0] https://code.sololearn.com/cRnd4TG5Z6ot/?ref=app

+3

🌱Zuhal🐛🌿 You can also do it like this :👇 fruits = {1:"Strawberry",2:'Banana',3:'Apple'} Not_eaten_with = {3:'Apple',2:'Banana',1:"Strawberry"} for i in (1,2,3): print(fruits[i]+ " shouldn't be eaten with " + Not_eaten_with[(len(fruits)+1)-i]) https://code.sololearn.com/cgJ6925Duhio/?ref=app

+1

I think you should create two dictionary like this then u can access it easily and your code will be simpler as well as well understandable. fruits={1:'Strawberry',2:'Banana',3:'Apple'} not_eaten={1:'Apple',2:'Strawberry',3:'Banana'} for i in fruits.keys(): print(fruits[i]+" shouldn't eaten with "+not_eaten[i]) https://code.sololearn.com/cSw24vE62Rf3/?ref=app