1

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?

T3KBAU5
  • 1,861
  • 20
  • 26
Jane
  • 11
  • 1
  • 5

2 Answers2

3

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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thank you for your response so fast but it is not recognizing the first line? – Jane Nov 21 '14 at 21:14
  • For your code it would be `for key, value in Dictionary.items():`, i had a different name for my variable – Cory Kramer Nov 21 '14 at 21:14
  • Thank you that line is not returning a traceback now but nothing is coming up it just returns blank. Sorry to be a pain but I've been trying to do this for a long time, so thanks again for any help you can give me. – Jane Nov 21 '14 at 21:22
  • @Jane, you'll need to replace the last call to `print` in your example by the lines Cyber gave you (with `d` replaced by `Dictionary`). – Oliver W. Nov 21 '14 at 22:10
1

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)
Community
  • 1
  • 1
justengel
  • 6,132
  • 4
  • 26
  • 42