简体   繁体   中英

How to append two lists of a regular expression as a dict key value pairs

Iam fetching two regex values from a file, IP from str1 and ID from str2.

str1 =   <IPAddress>12.1.1.2</IPAddress>
str2 =   <Id>202</Id>
                



import re
str1 = re.compile('<IPAddress>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})<\/IPAddress>')
str2 = re.compile('<Id>(\d+)<\/Id>')
regexList = [str2,str1]
file = open('ip_list.txt')
file = file.read()

for x in regexList:
    ID = x.findall(file)
    IP = x.findall(file)

They both returned a list of 100's of elements.

How to create new dict with ID as a key and IP as a value?

Whaever way I try from google like zip etc etc , I'm getting result as:

ID = {'5988': '5988', '5989': '5989', '5982': '5982', '5983': '5983', '5980': '5980'}

IP = {'204.110.170.210': '204.110.170.210', '10.54.18.15': '10.54.18.15', '10.98.128.145': '10.98.128.145', '10.237.115.122': '10.237.115.122', '10.248.56.1': '10.248.56.1'}

Instead of:

 {5988:204.110.170.210,5989:10.54.18.15 ....respectively}

Please help

I hope this small example helps you to attain the desired result:

Assuming that str1 and str2 contain strings '12345' and 'abcde' respectively,

str1 = '12345'
str2 = 'abcde'

To convert them to a list with each letter being an item of the list:

str1= list(str1)
str2= list(str2)

Now str1= ['1', '2', '3', '4', '5'] and str2 = ['a', 'b', 'c', 'd', 'e']

The next step is to iterate through either of the lists, create an empty dictionary and fill the dictionary likewise:

dictionary={}
for i in range(len(str1)):
    dictionary[str1[i]] = str2[i]
    
print(dictionary)

will yield the following output: {'1': 'a', '2': 'b', '3': 'c', '4': 'd', '5': 'e'}

To create a new dict with keys ID and values IP , both in lists:

new_dict = dict(zip(ID, IP))

To append keys ID and values IP to an existing dict:

existing_dict.update(zip(ID, IP))

just rewrite your code as follows:

import re
str1 = re.compile('<IPAddress>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})<\/IPAddress>')
str2 = re.compile('<Id>(\d+)<\/Id>')
regexList = [str2, str1]
file = open('ip_list.txt')
file = file.read()

ID = str2.findall(file)
IP = str1.findall(file)
Your_target_Dictionary = dict(zip(ID, IP))

print(Your_target_Dictionary )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM