-3

Here's my code:

`tv_dict = {}
user_input = input()

file_open = open(user_input)
file_content = file_open.readlines()

new_content = []
for x in file_content:
    new_content.append(x.strip())

list_len = len(new_content) // 2
loop_cy = 1
k = -1
v = -2

while loop_cy <= list_len:
    key = new_content[k]
    value = new_content[v]
    tv_dict[key] = value
    k += 2
    v += 2
    loop_cy += 1

val_sort1 = {k:[v for v in tv_dict.keys() if tv_dict[v] == k] for k in set(tv_dict.values())} 
val_sort2 = dict(sorted(val_sort1.items(), key=lambda val:val[0]))

file_1a = ''.join("{}: {}\n".format(k, v) for k, v in val_sort2.items())
print(file_1a)`

I'm trying to print:

10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke, Law & Order
30: The Simpsons

But I'm getting:

10: ['Will & Grace']
12: ['Murder, She Wrote']
14: ['Dallas']
20: ['Gunsmoke', 'Law & Order']
30: ['The Simpsons']

NOTE: The dictionary keys MUST be outputted together if they have the same value. (As seen with Gunsmoke and Law and Order)

I can get:

10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke 
20: Law & Order
30: The Simpsons

But sorting by values brings back the brackets and quotes.

  • `file_1a = ''.join("{}: {}\n".format(k, ', '.join(v)) for k, v in val_sort2.items())`? As a side note, if your only problem with the output is `print`ing, please *only* include that in the question along with a sample of the data before your final step. Everything except for a literal definition of `val_sort2` and the last 2 lines are unnecessary in your first code block to demonstrate the problem. – Axe319 Apr 11 '23 at 15:40

2 Answers2

0

You just need to join the values of your lists together with a comma. Try something like this:

file_1a = ''.join("{}: {}\n".format(k, ", ".join(v)) for k, v in val_sort2.items())
print(file_1a)`
jprebys
  • 2,469
  • 1
  • 11
  • 16
0

Use the join method to separate the list items with commas.

D = { 10: ['Will & Grace'],
12: ['Murder, She Wrote'],
14: ['Dallas'],
20: ['Gunsmoke', 'Law & Order'],
30: ['The Simpsons'] }

for key in sorted(D):
    print(f"{key}:",", ".join(D[key]))

10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke, Law & Order
30: The Simpsons

If you need it all to be in a single string, you can use join to combine the lines with a new-line separator ("\n"):

file_1a = "\n".join(f"{key}: "+", ".join(D[key]) for key in sorted(D))
Alain T.
  • 40,517
  • 4
  • 31
  • 51