2

Following Creating polygon from 2 txt files (Parent ID + Coordinates) from a few weeks ago, the script works very well. Now I need to reverse the process in order to update the Z value in the original text file describing a mesh.

From a first table of Points coordinates (Nnodes, resulting from Export Feature Attribute to ASCII):

 #Nnodes
 # X Y ID Z
 4403607.48  5788195.96  56362  87.6
 4403550.41  5788192.5  56951  93.4

I want to update the Z value from Nnodes to Mesh_orig,using the Point IDs as common keys

 # Mesh_orig
 #Geom ID X Y Z
 ND 56362 4403607.48 5788195.96 86.1
 ND 56951 4403550.41 5788192.5 91.3

It prints only the last row of Nnodes instead of the whole updated mesh_dict.

 with open (r'text2.txt','r+') as Mesh: 
      for row in Mesh:
          if row.startswith('ND'): 
              Inline= row.split()
              mesh_dict={Inline[1]:Inline[4]}
              KeyM = mesh_dict.keys()
              ValueM = mesh_dict.values()    

 with open (r'Text1.txt','r') as Npoint:
     for KeyM in mesh_dict:
         for lines in Npoint:
             Outlines= lines.split()
             point_dict={Outlines[-2]:Outlines[-1]}
             KeyP = point_dict.keys()
             ValueP = point_dict.values()
             if KeyM in point_dict:
                    point_dict.update(mesh_dict) 
                    print str(KeyM)+", "+str(ValueP)

Where is it going wrong?

0

2 Answers 2

4

When you're trying to assign the key to mesh_dict in the first loop you're actually overwriting it with a new dictionary on every iteration of the loop. Instead you should define the dictionary outside the loop and then set the dictionary values like so:

mesh_dict {}
for row in Mesh:
    if row.startswith('ND'):
        Inline= row.split()
        mesh_dict[Inline[1]] = Inline[4]
0
1

Here is the working code updating one of two dictionaries based on common keys:

Mesh_dict={}
Point_dict={}
Mesh = open (r'short3.txt','r+')  
for row in Mesh:
   # extract lines describing one type of geometry
    if row.startswith('ND'): 
    Inline= row.split()
    IDM = Inline[1]
    ZM = Inline[4]
    # actualise the dictionary of original data
    Mesh_dict[IDM]=ZM

Npoint= open (r'new_pt.txt','r')
for lines in Npoint:
    Outlines= lines.split()                
    IDP = Outlines [-2]
    ZP = Outlines[-1]
    Point_dict [IDP]=ZP      
for k1,v1 in Mesh_dict.items():
    for k2,v2 in Point_dict.items():
        if k1 ==k2:
           Mesh_dict[k1] = v2 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.