Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

Compare 2 dictionary and extract the other values in python

I have a parent dictionary

parent = [
  {
    "user": "[email protected]",
    "type": "Product Team",
    "message": "Developer",
    "employeeId": 101
  },
  {
    "user": "[email protected]",
    "type": "Product Team",
    "message": "Developer",
    "employeeId": "102"
  }
]

My input is

body = {"employeeId":102}

My input will vary for testing

body = {"employeeId":101}

body = {"employeeId":103}

I have search in parent dictionary and retrieve the user employeeId and message if it matches employeeId

  • I need to iterate over the parent dictionary
  • once I found the first match then i have to break out from the loop
  • if not i need to continue the loop
  • if success i need to return a dictionary
  • if employeeId doesnot match in parent dict then it should say employeeId doesnot exist

My code is below

def noid():
    return "No ID"
def new_f():
    for conf in parent :
        if int(conf["employeeId"]) == int(body['employeeId']):
             user = conf['user']
             employeeId= conf["employeeId"]
             message = conf["message"]
             return {'user': user, 'employeeId': employeeId, 'message': message}
             break
        else:
            continue
        return noid()
new_f()

In my code only employeeId:101 is working only for first element is working./ Only first dictionary getting success

question from:https://stackoverflow.com/questions/65905345/compare-2-dictionary-and-extract-the-other-values-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

user, employeeId, message = [''] * 3 # define variables before loop
found = False
for x in parent:
  if int(x['employeeId']) == int(body['employeeId']):
    user = x['user']
    employeeId = x["employeeId"]
    message = x["message"]
    found = True
    break
if found:
  print(user, employeeId, message)
else:
  print("Not found!")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...