简体   繁体   中英

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 – eg, 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

Use str.split() :

with open('one.txt') as f:
    d = dict(l.strip().split(':') for l in f)

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'}

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