简体   繁体   English

遍历存储在字典值中的列表

[英]Iterate over lists stored in dict values

I can't find anything that solves my problem. 我找不到能解决我问题的任何东西。

I have a function testdata() that returns data slices as a dictionary. 我有一个函数testdata(),将数据切片作为字典返回。 The keys are numbered as text (with a leading zero) for reference. 键以文本编号(前导零)编号,以供参考。

The function returns the below dict... 该函数返回以下命令...

mydict = {}
some stuff here   
pprint(mydict)
{'01': [u'test1',
        u'test2',
        u'test3'],
 '02': [u'test4',
        u'test5',
        u'test6'],
 '03': [u'test7',
        u'test8',
        u'test9']
 }

I now want to send the slices's (01, 02, 03) key values, one by one to another function as a comma separated list/string. 现在,我想将切片的(01,02,03)键值一个接一个地发送到另一个功能,作为逗号分隔的列表/字符串。

So first iteration would be to access '01' and create the list 'test1,test2,test3' then send it as an argument to my other function analysis(arg). 因此,第一个迭代将是访问“ 01”并创建列表“ test1,test2,test3”,然后将其作为参数发送给我的其他函数analysis(arg)。

Here's what I have... 这就是我所拥有的...

getdata = testdata() # 
for x in getdata:
    incr = 0
    analysis(x['01': incr])
    incr += 1

I get the following error: 我收到以下错误:

ERROR:root:Unexpected error:(<type 'exceptions.TypeError'>, TypeError('slice indices must be integers or None or have an __index__ method',), <traceback object at 0x10351af80>)
    In [2]: dic
    Out[2]: 
    {'01': [u'test1', u'test2', u'test3'],
     '02': [u'test4', u'test5', u'test6'],
     '03': [u'test7', u'test8', u'test9']}

    In [6]: for k,v in dic.iteritems():
   ...:     print k,v
   ...:     
02 [u'test4', u'test5', u'test6']
03 [u'test7', u'test8', u'test9']
01 [u'test1', u'test2', u'test3']

So i guess you could just do a .. 所以我想你可以做一个..

analysis(k,v) 

analysis(x['01': incr]) when doing ['01': incr] you're using the list slice operator : , and is supposed to be used with integer indices. 在执行['01': incr]时使用analysis(x['01': incr]) ['01': incr]您正在使用列表切片运算符: ,并且应该与整数索引一起使用。 incr is an int , but '01' is a string. incr是一个int ,但是'01'是一个字符串。

If you only want to iterate of the dict values (the corresponding lists), its enough to do: 如果只想迭代dict值(相应的列表),则足以执行以下操作:

for key, the_list in mydict.iteritems():
    analysis(the_list)
keys = list(getdata) # Create a `list` containing the keys ('01', '02', ...)
sort(keys) # the order of elements from `list` is _unspecificed_, so we enforce an order here
for x in keys:
    css = ",".join(getdata[x]) # Now you have css = "test1,test2,test3"
    analysis(css) # dispatch and done

Or, even more succinctly (but with the same internal steps): 或者,更简洁(但具有相同的内部步骤):

for x in sorted(getdata):
    analysis(",".join(getdata[x]))

As for your error, it's telling you that you can't use a string in slice notation. 至于您的错误,它告诉您不能在切片表示法中使用字符串。 Slice notation is reserved for [lo:hi:step] , and doesn't even work with dict anyway. 切片标记法是为[lo:hi:step]保留的,甚至对dict也无效。 The easiest way to "slice" a dict is through a dict comprehension. “切片” dict的最简单方法是通过对字典的理解。

Here's an example step by step of how this could be done.. 这是逐步执行此操作的示例。

gendata = {
 '01': [u'test1',u'test2',u'test3'],
 '02': [u'test4',u'test5',u'test6'],
 '03': [u'test7',u'test8',u'test9']
 }

#iterate over the keys sorted alphabetically 
#   (e.g. key=='01', then key=='02', etc)

for key in sorted(gendata):  
    value_list = gendata[key]  # e.g. value_list=['test1', 'test2, 'test3']
    joined_string = ','.join(value_list) # joins the value_list's items with commas
    analysis(joined_string) #calls the function with 'test1,test2,test3'

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

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