3

I have a text file (one.txt) that contains an arbitrary number of key‐value pairs (where the key and value are separated by a colon – e.g., x:17). Here are some (minus the numbers):

  1. mattis:turpis
  2. Aliquam:adipiscing
  3. nonummy:ligula
  4. Duis:ultricies
  5. nonummy:pretium
  6. urna:dolor
  7. odio:mauris
  8. lectus:per
  9. quam:ridiculus
  10. tellus:nonummy
  11. consequat:metus

I need to open the file and create a dictionary that contains all of the key‐value pairs.

So far I have opened the file with

file = []
with open('one.txt', 'r') as _:
    for line in _:
        line = line.strip()
        if line:
            file.append(line)

I opened it this way to get rid of new line characters and the last black line in the text file. I am given a list of the key-value pairs within python.

I am not sure how to create a dictionary with the list key-value pairs. Everything I have tried gives me an error. Some say something along the lines of

ValueError: dictionary update sequence element #0 has length 1; 2 is required

tshepang
  • 12,111
  • 21
  • 91
  • 136
cmal3
  • 33
  • 1
  • 4

2 Answers2

5

Use str.split():

with open('one.txt') as f:
    d = dict(l.strip().split(':') for l in f)
orlp
  • 112,504
  • 36
  • 218
  • 315
2

split() will allow you to specify the separator : to separate the key and value into separate strings. Then you can use them to populate a dictionary, for example: mydict

mydict = {}
with open('one.txt', 'r') as _:
    for line in _:
        line = line.strip()
        if line:
            key, value = line.split(':')
            mydict[key] = value
print mydict

output:

{'mattis': 'turpis', 'lectus': 'per', 'tellus': 'nonummy', 'quam': 'ridiculus', 'Duis': 'ultricies', 'consequat': 'metus', 'nonummy': 'pretium', 'odio': 'mauris', 'urna': 'dolor', 'Aliquam': 'adipiscing'}
Joe Young
  • 5,749
  • 3
  • 28
  • 27
  • Thank you! This worked. I did not realize how simple of a fix my script would be to make it into dictionaries. I am new to programming and have been working on this one part for most of the day. Thank you thank you! – cmal3 Sep 14 '15 at 22:46