Home > Software engineering >  Turning text file into dictionary when the same keys appear multiple times
Turning text file into dictionary when the same keys appear multiple times

Time:09-22

I have a text file that looks like this:

tomato 7000
potato and pear 8000
prunes 892
tomato 8
carrot 600
prunes 3

To turn it into a dictionary that ignores the lines where there are more words (which is what I want, so potato and pear are ignored, which is fine), I wrote:

with open("C:\\path\\food.txt", encoding="utf-8") as f_skipped:
    result = {}
    for line in f_skipped:
        try:
            k, v = line.split()
        except ValueError:
            pass
        else:
            result[k] = v
        

But since there can't be duplicate keys, it takes the value that appears later, so tomato and prunes have values 8 and 3, respectively. Is there any way of taking only the first appearance and ignoring the later once?

I thought of keeping my code and just turning the text around (sounds a bit silly) or detecting whether there are duplicate words (the latter is a bit risky since there are lots of rows with many words that I simply wanna ignore anyway).

CodePudding user response:

Try this .get(key) method of the dictionary will return None if the key doesn't exit otherwise return the value for the key. so you can use it in if condition. I hope this is what you want by reading your question.

filename = "text.txt"
with open(filename, encoding="utf-8") as f_skipped:
    result = {}
    for line in f_skipped:
        try:
            k, v = line.split()
        except ValueError:
            pass
        else:
            if result.get(k) is None: 
                result[k] = v

    print(result)

Output

py code.py
{'tomato': '7000', 'prunes': '892', 'carrot': '600'}

CodePudding user response:

Try this:-

with open('food.txt') as food:
    D = {}
    for line in food:
        t = line.split()
        k = ' '.join(t[0:-1])
        if not k in D:
            D[k] = t[-1]
    print(D)
  • Related