Home > Software design >  Python search and replace whilst caching
Python search and replace whilst caching

Time:10-07

I'm attempting to search and replace using information from 2 lists, this is whilst caching any replacements that have been done so the same corresponding values can be given.

For example, I have the following -

names = ["Mark","Steve","Mark","Chrome","192.168.0.1","Mark","Chrome","192.168.0.1","192.168.0.2"] 

type = ["user","user","user","process","address","user","process","adress","address"]

And I'm hoping to get the following output -

{
"Mark":"user1",
"Steve":"user2",
"Chrome":"process1",
"192.168.0.1":"adress1",
"192.168.0.2":"adress2"
}

So trying to use the type in the the 2nd list to determine the item in the first list's corresponding value.

Hope this makes sense, is this possible? Any help would be appreciated.

CodePudding user response:

I would recommend you use a dictionary personally.

names = {
    "Mark": "user",
    "Steve": "user2",
    "Chrome": "process1",
    "192.168.0.1": "address1",
    "192.168.0.2": "address2"
}

print(names["Mark"])

By using this dictionary you can precisely tap into the name you'd like to information of or anything else you want. It is also a little more readable

CodePudding user response:

To form a dictionary from said values you can iterate the range and access values with the same index:

output = {names[i]: types[i] for i in range(len(names))}

Also refrain from using variable name type because it's already taken by a builtin Python syntax.

  • Related