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

Time:08-09

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.

CodePudding user response:

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')]

CodePudding user response:

Per advice from responses. I did the below and it worked for me:

#This got the results into a separate list (variable).

res_1 = list()
for x in d:
 A = d[x]
 res_1.append(A)

Thanks everyone.

  • Related