问题
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