Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Delete corresponding values with different Keys from Dictionary

I am new to python and I am writing Flight Booking system program .I got stuck up on delete while deleting the passenger details because I have Dictionary with multiple Keys and the values for the Keys are in separate individual List.

I tried multiple ways using pop function it is deleting only particular Key and the corresponding values

How to delete the all the values of the Passenger Detail with Different Keys.

for eg: is the user enter 'tes' then I need to delete corresponding flightId,Age,destination,dlytype,source

I am getting User input as below

   Passenger = raw_input("Enter Name to delete")

Dictionary value shows as below:

  {'Passenger': ['tes', 'ssss'],
  'FlightId': ['ssss', 'tre'],
   'Age': ['12', '34'], 
    'Destination': ['ssss', 'ssssss'],
    'Flytype': ['economy', 'business'],
   'Source': ['sss', 'sssss']}

Dictionary declared:

          Name_list=[]
          Age_list=[]
          Source_list=[]
          Destination_list=[]
          Flytype_list=[]
          FlightId_list=[]

     Passenger_dict= {'Passenger':Name_list,
            'Age':Age_list,
            'Source':Source_list,
            'Destination':Destination_list,
            'Flytype':Flytype_list,'FlightId':FlightId_list}

Please help on this.

Thanks in Advance

question from:https://stackoverflow.com/questions/65871161/delete-corresponding-values-with-different-keys-from-dictionary

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

1 Answer

0 votes
by (71.8m points)

Better data structure to store you data will be list of dicts where each dict will represent one passenger object. (Or, if something is unique for passenger, like passenger_id, use that to create dict of dicts with passenger_id as key of your main dict)

However, in your current data structure, you can do something like this:

  • Step 1: Get index of passenger based on Passenger. It will raise ValueError exception if name not found in the list

    passenger_index = Passenger_dict['Passenger'].index(Passenger)
    
  • Step 2: Delete element at passenger_index index from all the lists

     for v in Passenger_dict.values():
         del v[passenger_index]
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...