简体   繁体   中英

Reading text file into dictionary

my text file has a format:

car,coche,auto
chair,silla,stuhl,sella

The first element is the english word. I want to create a dictionary that does the following and returns dictionary.

dict =        {'coche'  : 'car',
               'auto'   : 'car',
               'stilla' : 'chair',
               'stuhl'  : 'chair',
               'sella'  : 'chair' }

I cannot use any built in function just loops and basic functions.

I know I want to:

  • split the elements of each line
  • set the first item as the key
  • assign the second item as a value
  • assign the following values to the same key
    open_file = open(words_file_name, 'r')
    conversions = {}
    for line in open_file:
        piece = open_file.split(',')
        key = piece[0]
        conversions[key] = 0 
        if piece not in conversions:
            conversions[piece] = 1
        conversions[piece] += 1
    for key, value in conversions:
        return conversions

I have continuously gotten key errors, etc.

Not tested but should work I think. Pop the first item, and use it as a value for all other words.

d = {}
with open('your-file.txt', 'r') as fhin:
    for line in fhin:
        words = line.strip().split(',')
        en_word = words.pop(0)
        for word in words:
            d[word] = en_word

You can just do this using dict.fromkeys

open_file = open(words_file_name, 'r')
conversions = {}
for line in open_file:
    val, keys = line.strip().split(',', 1)
    conversions.update(dict.fromkeys(keys.split(','), val))

print (conversions)

Output

{'sella': 'chair', 'coche': 'car', 'stuhl': 'chair', 'silla': 'chair', 'auto': 'car'}

Your code is very close. It just seems that you have key and value backwards. The dictionary you are trying to create has the English word as the value and the non-English words as the keys of the dictionary.

open_file = open(words_file_name, 'r')
conversions = {}
for line in open_file:
    piece = line.split(',')
    value = piece[0]               # <- the first item will be the value
    for key in piece[1:]:          # <- iterate over the rest of the items in the line
        conversions[key] = value   # <- add the key:value pair to the dictionary
print(conversions)

simple loops:

open_file = open('read.txt', 'r')
conversions = {}
for line in open_file:
    piece = line.rstrip().split(',') #rstrip to remove \n
    key = piece[0]
    for obj in piece[1:]:
        conversions[obj]=key
print (conversions)

Output :

{'sella': 'chair', 'coche': 'car', 'stuhl': 'chair', 'silla': 'chair', 'auto': 'car'}

it looks like you have a csv. You should try using csv.DictReader() from the csv module

import csv
csv_data=csv.DictReader(open('file_loc'))
for row in csv_data:
    #DoSomething  

this will make csv_data an OrderedDict , you can typecast it to Dict using dict(object)

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