Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dictionary
#1
hi i have this code with 4 files f.text, n.text, j.text, a.text
import os
currentPath =__file__

directoryPath = os.path.dirname(currentPath)
fileName = os.path.basename(currentPath)
print(directoryPath)
for _file in os.listdir(directoryPath):
     if _file.endswith(".text"):
        if (_file.split(".")[0] == "n"):
           selectedPath= os.path.join(directoryPath, _file)
           n=open(selectedPath, "r")
           for line in n:
             line =line.strip()  
             # print(line)
             n1=[]
             n1.append(line)
            #  print(n1)
             n2={ }
             for item in n1:
              key=['name']
              values=[item]
              n2=dict(zip(key,values))
             print(n2)  
        elif (_file.split(".")[0] == "f"):
           selectedPath= os.path.join(directoryPath, _file)
           f=open(selectedPath, "r")
           for line in f:
              line = line.strip()  
             # print(line)
              f1=[]
              f1.append(line)
            #   print(f1)
              f2={ }
              for item in f1:
               key=['family']
              values=[item]
              f2=dict(zip(key,values))
              print(f2)
        elif (_file.split(".")[0] == "a"):
           selectedPath= os.path.join(directoryPath, _file)
           a=open(selectedPath, "r")
           for line in a:
             line = line.strip()  
             # print(line)
             a1=[]
             a1.append(line)
            #  print(a1)
             a2={ }
             for item in a1:
               key=['age']
             values=[item]
             a2=dict(zip(key,values))
             print(a2)
        else: 
            selectedPath= os.path.join(directoryPath, _file)
            j=open(selectedPath, "r")
            for line in j:
              line = line.strip()  
             # print(line)
              j1=[]
              j1.append(line)
            #   print(j1)
              j2={ }
              for item in j1:
               key=['job']
              values=[item]
              j2=dict(zip(key,values))
              print(j2) 

result =dict(n2)
result.update(f2)
result.update(a2)
result.update(j2)

print(result)
the result is
Output:
{'name': 'ahmad', 'family': 'torabi', 'age': '45', 'job': 'manager'}
but i want the result like this
Output:
{'name': 'ahmad', 'family': 'torabi', 'age': '45', 'job': 'manager'},{'name': 'ali', 'family': 'rezaii', 'age': '32', 'job': 'driver'}
f.text:
rezaii
torabi
n.text:
ali
ahmad
j.text:
driver
manager
a.text:
32
45
Yoriz write May-21-2021, 08:57 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
You don't need all that repetitive code, you should create a function instead.

Here is a function that uses with to open the passed in file path, with will automatically close the file when done.
The for loop yields each stripped line, by using yield it turns into a generator function
def yield_file(file_path):
    with open(file_path, 'r') as reader:
        for line in reader:
            yield line.strip()
The following makes an iterator for each of the files
names = yield_file('n.text')
familys = yield_file('f.text')
ages = yield_file('a.text')
jobs = yield_file('j.text')
Now zip each iterator together to create the dictionary
keys = ('name', 'family', 'age', 'job')
result = [dict(zip(keys, values)) for values in zip(names, familys, ages, jobs)]
print(result)
Output:
[{'name': 'ali', 'family': 'rezaii', 'age': '32', 'job': 'driver'}, {'name': 'ahmad', 'family': 'torabi', 'age': '45', 'job': 'manager'}]

Removing some more repetitions.
def yield_file(file_path):
    with open(file_path, 'r') as reader:
        for line in reader:
            yield line.strip()


keys = ('name', 'family', 'age', 'job')
file_lines = [yield_file(f'{key[0]}.text') for key in keys]

result = [dict(zip(keys, values)) for values in zip(*file_lines)]
print(result)
Reply
#3
Hi
thank you for your help
if it is possible run code
because I faced with error
PS C:\Users\2016\Desktop\amoozesh python> & C:/Users/2016/AppData/Local/Programs/Python/Python37/python.exe "c:/Users/2016/Desktop/amoozesh python/.vscode/n.py
Traceback (most recent call last):
File "c:/Users/2016/Desktop/amoozesh python/.vscode/n.py", line 14, in <module>
result = [dict(zip(keys, values)) for values in zip(*file_lines)]
File "c:/Users/2016/Desktop/amoozesh python/.vscode/n.py", line 14, in <listcomp>
result = [dict(zip(keys, values)) for values in zip(*file_lines)]
File "c:/Users/2016/Desktop/amoozesh python/.vscode/n.py", line 2, in yield_file
with open(file_path, 'r') as reader:
FileNotFoundError: [Errno 2] No such file or directory: 'n.text'
PS C:\Users\2016\Desktop\amoozesh python>
Reply
#4
(May-22-2021, 07:39 AM)coral_raha Wrote:
Error:
FileNotFoundError: [Errno 2] No such file or directory: 'n.text'
Make sure the file is there and it is in the right folder.

(Please use [error]...[/error] tags when you post errors.)
Reply
#5
Hi again
Thank you for your help and I appreciate
if it is possible help me to have this result from code at the end :
Output:
{"PERSON1":{'name': 'ali', 'family': 'rezaii', 'age': '32', 'job': 'driver'}, "PERSON2":{'name': 'ahmad', 'family': 'torabi', 'age': '45', 'job': 'manager'}}
Reply
#6
def yield_file(file_path):
    with open(file_path, 'r') as reader:
        for line in reader:
            yield line.strip()


keys = ('name', 'family', 'age', 'job')
file_lines = [yield_file(f'{key[0]}.text') for key in keys]

result = {f'PERSON{index}': dict(zip(keys, values))
          for index, values in enumerate(zip(*file_lines), 1)}
print(result)
Output:
{'PERSON1': {'name': 'ali', 'family': 'rezaii', 'age': '32', 'job': 'driver'}, 'PERSON2': {'name': 'ahmad', 'family': 'torabi', 'age': '45', 'job': 'manager'}}
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020