0

I need to take a series of text inputs, and combine them with a number and some formatting. The catch is that I don't know how many elements the series of inputs will have beforehand. I know this would be easy to do for a set number of inputs, but I need a function that will iterate as many as necessary.

So basically I need to take 'apple banana cherry ...' and '5' and output:

str('{"apple": 5, "banana": 5, "cherry": 5, "...": 5}')

This is what I have so far:

print("Enter fruits:")
fruits = [x for x in input().split()]
print("Enter Maximum Fruits per Day")
maxfruit = input()
def maxfruitfuncstep1(x,y):
    return str('"' + x + '"' + ": " + y)
for i in fruits: 
    print("{" + maxfruitfuncstep1(i,maxfruit) + "}")

but that just gives me output:

{"apple": 5}
{"banana": 5}
{"cherry": 5}

How can I get the function to run horizontally within the printout? I've tried using ",".join but that just gave me:

",a,p,p,l,e,",:, ,5
1
  • Not sure, what exactly your question here is. Maybe this? Commented Dec 9, 2018 at 22:43

2 Answers 2

1

This is what you want:

fruits = ["apple", "banana", "cherry"]
maxfruit ="5"
print("{" + ", ".join(fruit + ": " + maxfruit for fruit in fruits) + "}")

Another solution is simply:

repr({fruit: maxfruit for fruit in fruits})
Sign up to request clarification or add additional context in comments.

3 Comments

upvoting yours, better than mine :D
is using "for listname in listname" the key? I feel like it wasn't letting me do "for i in listname" in the middle of the line
I don't understand your question.
0

One way is something like:

fruits = ['banana', 'strawberry', 'cherry']

max_num = 5

from collections import defaultdict

result = defaultdict(dict)

for x in fruits:
    result[x] = max_num

str(dict(result))

"{'banana': 5, 'strawberry': 5, 'cherry': 5}"

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.