Skip to content Skip to sidebar Skip to footer

Dict And List Manipulation Python

I have two files one has key and other has both key and value. I have to match the key of file one and pull the corresponding value from file two. When all the key and value are in

Solution 1:

I thought @three_pineapples's eval manner is quite good and brilliant,

Here is an alternative one which only manipulate string:

edges = {}
with open("Input_1.txt", "r") as edge_data:
    for row in edge_data:
        k, v = row.strip().split(")") # split as key, value
        k = " ".join(i.strip("'") for i in k.strip("(").split(", ")) # clean unwanted symbol and merge together
        v = v.strip(" []").split(", ") # get list value
        edges[k] = v

with open("Input_2", "r") as classified_data:
    for row in classified_data:
        k = row.strip();
        for v in edges.get(k, []):
            print k, v

Solution 2:

Use pattern matching

import re
rec = re.compile(r"\('(\d+)',\s*'(\d+)'\)\s*\[(.*)\]")
matches = rec.match("('3350', '2542') [6089.0, 4315.0]")
print matches.groups()
print int(matches.group(1))
print int(matches.group(2))
print map(float, matches.group(3).split(','))

The output is

('3350', '2542', '6089.0, 4315.0')
3350
2542
[6089.0, 4315.0]

To save the data

a = int(matches.group(1))
b = int(matches.group(2))
data = map(float, matches.group(3).split(','))
edges[a,b] = data

To get data and print the output

c = edges.get((a,b), edges.get((b,a)))
for value in c:
   print "%s %s %s\n" % (a,b, value)

Solution 3:

I would suggest splitting the string on a different caharacter, say ')'

So you would do something like:

with open('Input_1.txt', 'r') as edge_data:    
    for row in edge_data:
        col = row.strip().split(')')

You then want to convert the string representation of a tuple and a list, into something you can work with. You can do this by using eval()

        key = eval(col[0]+')') # note I add the bracket back in that we split on
        value = eval(col[1])
        edges[key] = value

You now have a dictionary edges with keys that match the tuple in file one and values that contain the associated lists

When you read in file 2, you will need to add another loop that iterates over the entries in the list. For example, something like

for c in edges[(a,b)]:
    outfile.write("%s %s %s\n" % (a,b,c))

This will allow you to write a line to your output file for each entry in the list you read in from the first file.


Post a Comment for "Dict And List Manipulation Python"