简体   繁体   English

每个键具有多个值的Dict上的Python For循环

[英]Python For loop on Dict with multiple Values per Key

I want to create a Dict with 2 Values per each Key. 我想创建一个Dict,每个键具有2个值。 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). 但是,最终,我只想遍历每个键一次,然后在每个键的循环内,依次遍历Value中的2个元素。

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. 我正在使用PySpark,但这没关系,它是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只是一个列表,它是键k的值。 v[0] is the first item of value and v[1] is the second item. v[0]是值的第一项,而v[1]是第二项。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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