Home > Net >  problem with spaces in a sorted dictionary with lambda
problem with spaces in a sorted dictionary with lambda

Time:08-09

I have a nested dictionary. I want to sort it firstly by points, secondly by wins ( if points are the same) and lastly by alphabet if wins is equal. At the end I must have the result exactly like :

    Spain  wins:1 , loses:0 , draws:2 , goal difference:2 , points:5
Iran  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4
Portugal  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4
Morocco  wins:1 , loses:2 , draws:0 , goal difference:-2 , points:3

My problem is with the space between wins,loses,...with the scorces. mine is like :wins: 1 but it must be wins:1 without any space. Here is my code:

dic={"Iran":{"wins":1,"loses":1,"draws":1,"goal difference":0,"points":4},{"Spain":{"wins":1,"loses":0,"draws":2,"goal difference":2,"points":5}},{"Portugal":{"wins":1,"loses":1,"draws":1,"goal difference":0,"points":4}},{"Morocco":{"wins":1,"loses":2,"draws":0,"goal difference":-2,"points":3}}}
sort_data=sorted(dic.keys(),key=lambda x:(-dic[x]["points"],dic[x]["wins"]))
for items in sort_data:
    x=dic[items]
    print(items," ",str(x).replace("'", "").replace("{","").replace("}", ""))

all is correct except the space in my output which is like:

Iran  wins: 1, loses: 1, draws: 1 , goal difference: 0, points: 4
Portugal  wins: 1, loses: 1, draws: 1, goal difference: 0, points: 4
Morocco  wins: 1, loses: 2, draws: 0, goal difference: -2, points: 3

CodePudding user response:

You could just add some more replace calls, replacing "," with " ," and ": " with ":" to add the spaces before commas, and remove those after colons. Note that your code would print three spaces after the country name, though, since another space in added as the separator between all things to be printed. Use sep="" to fix that.

for item in sort_data:
    print(item, "  ", str(dic[item]).replace("'", "").replace("{","").replace("}", "")
                                   .replace(",", " ,").replace(": ", ":"), sep="")

Alternatively, you could use a format-string to properly format the different key-value pairs in the way you like and then join those together with " , ":

for item in sort_data:
    print(item, " , ".join(f"{k}:{v}" for k, v in dic[item].items()), sep="  ")

CodePudding user response:

Using print with multiple arguments joins them with a space. Use either string concatenation or string formatting instead:

A = "aa"
B = "bb"
print(A, B)
# Prints 'aa bb'
print(A   B)
# Prints 'aabb'
print(f"{A}{B}")
# Prints 'aabb'
  • Related