#๐Ÿ”’ dictionary formatting

35 messages ยท Page 1 of 1 (latest)

oblique mantle
#

i have a dictionary in the format {x: [a, b, c...]} and i'd like to format it as x, a, b, c...
any ideas for how to go about this?

viscid fractalBOT
#

@oblique mantle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

midnight notch
#

Can you share the dictionary?

novel tartan
#

unpacking would make this quite simple

#

!e

data = {'x': ['a', 'b', 'c']}


for k, v in data.items():
    print(k, *v, sep=', ')
viscid fractalBOT
novel tartan
#

@oblique mantle still there?

oblique mantle
#

sorry, i am

#

i'll try that

#

what does sep do?

cedar mesa
#
>>> help(print)
Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.

    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
    file
      a file-like object (stream); defaults to the current sys.stdout.
    flush
      whether to forcibly flush the stream.
oblique mantle
#

thank you! it works well

oblique mantle
novel tartan
#

since print accepts unlimited arguments, it will place each item as a separate argument

#
data = ['a', 'b', 'c']

print(*data)
# Is basically the same as
print(data[0], data[1], data[2])
#

these are basically the same

oblique mantle
#

okay cool that makes sense

novel tartan
#

but with *data, it doesn't matter how many items there are inside the list

oblique mantle
#

so would it be the same as going

#

data[0:]?

novel tartan
#

no, because that's still a list

oblique mantle
#

isn't that a list as well?

novel tartan
#

data[0] is not a list

#

it's a string

#

"unpacking" is taking the elements of the list one at a time and passing them as arguments

#

!e

data = ['a', 'b', 'c']

print(data)
print(*data)

viscid fractalBOT
novel tartan
#

look at the difference

oblique mantle
#

that makes sense. thank you for the help!

novel tartan
oblique mantle
#

!close

viscid fractalBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.