简体   繁体   中英

Python For loop on Dict with multiple Values per Key

I want to create a Dict with 2 Values per each Key. I don't know whether it's better to make the Values for each Key a List, or another Dictionary. But, ultimately I want to loop through each Key once only, and then within the loop of each key, loop through the 2 elements in the Value (in sequence).

I have this code:

dic = {'%serial_number%':['SERIAL_NUMBER :: (\w+)','number'],'%sw_version%':['SW_VERSION :: HR6400 ([\d\.\-]+)','ver']}
def match_regex(text):
    for k,v in dic.iteritems():
        for v1 in v:
            print(text,k,text,v1[0],v1[1])
match_regex(df.value)

Which outputs the following:

(Column<value>, '%sw_version%', Column<value>, 'S', 'W')
(Column<value>, '%sw_version%', Column<value>, 'v', 'e')
(Column<value>, '%serial_number%', Column<value>, 'S', 'E')
(Column<value>, '%serial_number%', Column<value>, 'n', 'u')

The Output I WOULD LIKE would appear like this:

(Column<value>, '%serial_number%', Column<value>, 'SERIAL_NUMBER :: (\w+)', 'number')
(Column<value>, '%sw_version%', Column<value>, 'SW_VERSION :: HR6400 iDirect ([\d\.\-]+)', 'ver')

I am using PySpark, but it shouldn't matter, it's Python 2.7. THE FUNCTION needs to be generic, so I only want to reference it by index, NOT by the string content.

There is no need of a loop to display each items in value.

v is simply a list which is the value for the key k . v[0] is the first item of value and v[1] is the second item.

dic = {'%serial_number%':['SERIAL_NUMBER :: (\w+)','number'],'%sw_version%':['SW_VERSION :: HR6400 ([\d\.\-]+)','ver']}

def match_regex(text):
    for k, v in dic.iteritems():
        print(text,k,text,v[0],v[1])

match_regex(df.value)

# (Column<value>, '%serial_number%', Column<value>, 'SERIAL_NUMBER :: (\w+)', 'number') 
# (Column<value>, '%sw_version%', Column<value>, 'SW_VERSION :: HR6400 iDirect ([\d\.\-]+)', 'ver')

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