Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dictionary that contains key‐value pairs from a text file

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

like image 408
cmal3 Avatar asked Jan 31 '26 01:01

cmal3


2 Answers

Use str.split():

with open('one.txt') as f:
    d = dict(l.strip().split(':') for l in f)
like image 51
orlp Avatar answered Feb 02 '26 23:02

orlp


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'}
like image 40
Joe Young Avatar answered Feb 02 '26 21:02

Joe Young