Search code examples
pythonlistdictionarykey-value-store

Is there a way to extract the Key and Field values from a dictionary into separate variables?


I have a dictionary with items that look like this:

{'33515783': [('ID', '33515783'),
('Location', 'madeuptown'),
('Address1', ' 1221 madeup street')],..etc

Is there a way to have the Key values (33515783) be in a separate variable and then everything in the list from [('ID' -------street')] in another variable ?

so for example:

Variable 1: 33515783

Variable 2: [('ID', '33515783'), ('Location', 'madeuptown'), ('Address1', ' 1221 madeup street')]

I was able to get the Variable 1 (Keys) correctly using this:

for x in d:
  ID = x

But I do not know what to do for the field portion.

Thank you for your time.


Solution

  • You can use dictionary.items() to get key, value pairs and unpack them with a loop to get them seperately in two variables. Something like this.

    a = {'33515783': [('ID', '33515783'),
    ('Location', 'madeuptown'),
    ('Address1', ' 1221 madeup street')]}
    
    for key, value in a.items():
        print(key)
        print(value)
    

    Output:

    33515783
    [('ID', '33515783'), ('Location', 'madeuptown'), ('Address1', ' 1221 madeup street')]