1

I have a problem by reading my .txt file and save it in dict. This is my following code:

 def __init__(self, folder_path):
    os.chdir(folder_path)
    self._path = folder_path
    self._data = {}
    _files = glob.glob('*.txt')
    _temp = {}
    for dat in _files:
        _temp.clear()
        with open(dat,"r",encoding="utf-8") as f:
            for item in f:
                if item != '\n':
                    custom = (item.strip('\n').split('='))
                    _temp[custom[0]] = custom[1]
                    self._data[dat] = _temp
    print(self._data)

And this is the output:

{'RC0603FR-07100KL.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}, 
'RC0805FR-07100KL.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}, 
'TPS73033DBVT.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}}

The exactly problem is, that the last value override the all other one. For ex. this is how it should look like:

{'RC0603FR-07100KL.txt': {'count': '100', 'value': '100k', 'package': 'Chip'}, 
'RC0805FR-07100KL.txt': {'count': '50', 'value': '10n', 'package': 'Cap'}, 
'TPS73033DBVT.txt': {'count': '20', 'value': 'TPS73033', 'package': 'SOT-23-5'}}

What I'm doing wrong?

A sample of .txt file:

count=50
value=100k
unit=Ohm
package=0603
description=Chip Resistor
supplier=Digikey
supplierpartnumber=311-100KHRCT-ND
price=0.009
currency=CHF
srky
  • 350
  • 2
  • 4
  • 12
  • Can you provide a sample of the text files? – jordanm Apr 16 '20 at 18:34
  • Your problem is that you are assigning the same dict `_temp` to all of the `self._data`. You need to make a copy of the dict for each `self._data` or initialise the dicts and assign values to it. check [this](https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy) – jkhadka Apr 16 '20 at 18:36
  • @jordanm yes, i add one sample the other ones look like this one but with other values for count,unit etc. – srky Apr 16 '20 at 18:37
  • @hadik hmm... i dont get it really but i will try it – srky Apr 16 '20 at 18:40

1 Answers1

0

You need to copy the dict. Replace self._data[dat] = _temp by self._data[dat] = _temp.copy()

Check this example:

data = [
    {'a':1, 'b':1},
    {'a':2, 'b':2},
]
copieddata = []
temp = {}
for d in data:
    temp.clear()
    for k, v in d.items():
        temp[k] = v
    copieddata.append(temp)

This will have copieddata as:

[{'a': 2, 'b': 2}, {'a': 2, 'b': 2}]

Because, you are basically using the same variable temp and assign it to different elements of the list (copieddata). But what you want is that you want to create different dict and assign it to elements of the list, hence you need to copy the temp variable. That ensures new dict is created and not the same one is reused for all the elements of the list (copieddata). Below I used .copy() to add to the list, and works as expected.

data = [
    {'a':1, 'b':1},
    {'a':2, 'b':2},
]
copieddata = []
temp = {}
for d in data:
    temp.clear()
    for k, v in d.items():
        temp[k] = v
    copieddata.append(temp.copy())

Copied data is now :

[{'a': 1, 'b': 1}, {'a': 2, 'b': 2}]
jkhadka
  • 2,443
  • 8
  • 34
  • 56
  • @srky great that it works. [Check this to read more on copying the python objects or just assigning or referencing it.](https://docs.python.org/2/library/copy.html) – jkhadka Apr 16 '20 at 18:50