简体   繁体   中英

How to get rid of braces/curly brackets in a dictionary and make the dictionary vertical?

I have to import a txt file onto python and import it in to a dictionary. I then have to get rid of the braces/curly brackets and then display it vertically, and I have no idea how to do that.

This is the code I have created so far:

            Dictionary = {}

            with open('Clues.txt', 'r') as f:
                for line in f:
                    (key,val) = line[1], line[0]
                    Dictionary[key] = val

            print(Dictionary)

At the moment this is being displayed:

            {'&': 'L', '$': 'G', '£': 'J'}

But I need it to be displayed like :

            '&': 'L'
            '$': 'G'
            '£': 'J'

I have tried everything and nothing is working, any ideas?

You can iterate over the dictionary's items() and the format() the output.

for key, value in d.items():
    print('{}: {}'.format(key, value))

Output

&: L
$: G
£: J

Json is a JavaScript format for handling data, but pretty much any language can read and write it. https://docs.python.org/3.4/library/json.html

import json

d = json.loads(my_str_dictionary)
for key, value in enumerate(d):
    print(key, " : ", value)

JSON also has it's own printing if you would like to use that. From the json docs.

>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
    "4": 5,
    "6": 7
}

You can also use the ast literal_eval which can take a string and return a python object. It is still an eval, but it is a lot better than regular eval. Using python's eval() vs. ast.literal_eval()?

import ast

d = ast.literal_eval(my_str_dictionary)
for key, value in enumerate(d):
    print(key, " : ", value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM