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
JZ1987
  • 99
  • 4
  • Not sure, what exactly your question here is. Maybe [this](https://stackoverflow.com/q/493386/8881141)? – Mr. T Dec 09 '18 at 22:43

2 Answers2

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})
Julien
  • 13,986
  • 5
  • 29
  • 53
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}"
SmokeRaven
  • 111
  • 7