Iterate over a dict except for x item items

天涯浪子 提交于 2021-02-08 13:34:14

问题


I have a dict in this format:

d_data = {'key_1':value_1,'key_2':value_2,'key_3':value_3,'key_x':value_x,'key_n':value_n}

and I have to iterate over it's items:

for key,value in columns.items():
    do something

except for the pair:

'key_x':value_x

回答1:


You can use a list comprehension or generator expression to filter:

for key,value in (i for i in columns.items() if not i==('key_x',value_x)):
    do something



回答2:


Simply use the continue statement, to skip ahead to the next iteration of the for loop:

for key,value in columns.items():
    if key == 'key_x':
        continue
    # do something



回答3:


You can also iterate through the output of filter built-in method (which yields a generator in Python3+), this way:

>>> for x in filter('key_x'.__ne__, d_data):
        print(x, d_data[x])


key_3 value_3
key_n value_n
key_1 value_1
key_2 value_2 


来源:https://stackoverflow.com/questions/36184371/iterate-over-a-dict-except-for-x-item-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!