Home > Blockchain >  How to print a dictionary without any special characters?
How to print a dictionary without any special characters?

Time:11-24

myDict = {"word" : [10],
          "other word" : [16]}

I was wondering how I would be able to print this out in this format:

word 10
other word 16

CodePudding user response:

Iterate over the key/value pairs in the dict and print them line by line is a solid starting point for the majority of cases:

for key, value in myDict.items():
    print(key, *value, sep = " ")

You need to use the * or destructuring operator because your value is a list.

For a more in-depth examination of several examples, the following is an excellent example from the documentation: https://docs.python.org/3/tutorial/datastructures.html#looping-techniques

CodePudding user response:

Integer values vs list values in a dictionary

print a dictionary without any special characters

Your myDict isn't a dictionary with "special characters", it is, in fact, a dictionary with values as lists.

But in your case, those lists themselves have single items, and I am assuming that will remain the case.

{'key1': [list of values], 
 'key2': [list of values], 
 'key3': [list of values]}

In order to convert a dictionary with list values into a dictionary with just simple key, value pairs, try iterating over it using a dict comprehension and take only the first item from each of the values with v[0], as follows -

output = {k:v[0] for k,v in myDict.items()}
print(output)
{'word': 10, 'other word': 16}

Printing the key, value pairs in a dictionary

Now with the right data structure, you can print things the way you need -

for k,v in output.items():     #using previous "output"
    print(k,v)
    
word 10
other word 16

If you want to just print it in the way you have mentioned above, and not worry about fixing the dictionary then just use myDict directly and do this -

for k,v in myDict.items():    #Using original "myDict"
    print(k,v[0])             #<-----
    
word 10
other word 16
  • Related