Skip to content Skip to sidebar Skip to footer

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 numb

Solution 1:

Use str.split():

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

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

Post a Comment for "How To Create A Dictionary That Contains Key‐value Pairs From A Text File"