Home > Software design >  Dictionary of dictionaries as values and index as keys
Dictionary of dictionaries as values and index as keys

Time:01-04

I need to create a dictionary (let's name it general) from dictionaries. General is a dictionary that has other dictionaries as value and index ( in order of addition ) as key.

Sample General:

{
1: {'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}, #was added first 
2: {'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}, #was added next (second) 
3: {'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}, #was added third and so on 
}

Sample dictionary :

{'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}

I have a for loop that generates the above dictionaries, and I just need a way to append those to a general with a key that will be the order by which the dictionary is appended.

Sorry if unclear, I tried my best.

CodePudding user response:

You should use a list rather than a dictionary if you want to preserve insertion order. Dictionaries preserve insertion order as of Python 3.6. But, this fact isn't immediately obvious to most people, making your code harder to understand, and if you're running a version of Python earlier than 3.6, you can't rely on this behavior.

So, you have two options:

  1. Use a list and call .append() whenever you want to add to it.
  2. If you must use a dictionary for whatever reason, something like general[len(general) 1] = # dictionary to append will generate the keys you're looking for. But again, I would seriously suggest against this for the above mentioned reasons.

CodePudding user response:

This example assumes you want to manually enter the data:

general = {}
def add_to_dict():
    n = 0
    while True:
        n =1
        date = input("Enter date: "),
        time = input("Enter time: "),
        lat = input("Enter latitude: ")
        
        general[f'{n}'] = {'DATE':date,'TIME':time,'LAT':lat}

        another = input("Enter another? Y/N: ").capitalize().strip()
        if another == 'Y':
            another = True
            continue
        else:
            print(general)
            break
add_to_dict()
  •  Tags:  
  • Related