Python Dictionary infinite Traversal

Source: Internet
Author: User

#无限遍历dict, get value through key, nested dictionary has multiple identical keys, can get more than one key
Class GetValues (object):
def __init__ (self):
Pass

#无限遍历dict, get value through key, nested dictionary has multiple identical keys, can get more than one key
def get_target_value (Self,key, DIC, tmp_list):
"""
:p Aram Key: Target key value
:p Aram Dic:json Data
:p Aram Tmp_list: Used to store acquired data
: return:list
"""
If not isinstance (DIC, dict) or not isinstance (tmp_list, list): # format check for incoming data
Return ' argv[1] not a dict or argv[-1] not a list '

If key in Dic.keys ():
Tmp_list.append (Dic[key]) # Incoming data is present and stored in tmp_list
For Val in Dic.values ():
If Isinstance (Val, dict):
Self.get_target_value (Key, Val, tmp_list) # The value of the incoming data is a dictionary, it calls itself directly
Elif Isinstance (Val, (list, tuple)):
Self.get_value (Key, Val, tmp_list) # The value of the incoming data is a list or tuple, then the get_value is called
Else
For value in Dic.values (): # Traversal of the value of the incoming data if it does not conform
If Isinstance (value, dict):
Self.get_target_value (key, Value, Tmp_list) # The value of the incoming data is a dictionary, it calls itself directly
Elif isinstance (value, (list, tuple)):
Self.get_value (key, Value, Tmp_list) # The value of the incoming data is a list or tuple, then the get_value is called
Return tmp_list

#循环判断是否需要遍历value, Get_target_value Sub-method
def get_value (Self,key, Val, tmp_list):
For Val_ in Val:
If Isinstance (Val_, dict):
Self.get_target_value (Key, Val_, tmp_list) # The value of the incoming data is a dictionary, then the get_target_value is called
Elif isinstance (Val_, (list, tuple)):
Self.get_value (Key, Val_, tmp_list) # The value of the incoming data is a list or a tuple, it calls itself

Python Dictionary infinite Traversal

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.