Home > Software design >  there must be a better way or am I not thinking straight? for i, unused_and_only_to_fix_bug in
there must be a better way or am I not thinking straight? for i, unused_and_only_to_fix_bug in

Time:09-18

I was writing some code and was wondering whether there was a more elegant method.

data_to_parse = 
    {'unknown_key1': {'body': 'value1', 'subject': 'value1'}, 
    {'unknown_key2': {'body': 'value2', 'subject': 'value2'} 
    # goes on and on etc.

for i, unused_and_only_to_fix_bug in enumerate(data_to_parse):
        email_key_id = list(data_to_parse.keys())[i]
        email_info = data_to_parse[email_key_id]

When I remove unused_and_only_to_fix_bug it throws: ValueError: too many values to unpack (expected 1)

CodePudding user response:

Hard to understand what you are trying to achieve, but it seems like you are trying to access the dictionnary keys and value in a weird way in your for loop

if your goal is really getting each key, value association from a dictionnary that's how you are "supposed" to do :

for key, value in data_to_parse.items():
        email_key_id = key
        email_info = value

where if you have let's say a dictionnary = { "first_email_id": {'body': 'value1', 'subject': 'value1'}}

key will take the value of "first_email_id" and value will take the value of {'body': 'value1', 'subject': 'value1'}

  • Related