I have a question to get Python dictionary key, value value.

Asked 1 years ago, Updated 1 years ago, 65 views

input_value={AAA': {'aa1': ['a1', 'b1', 'c1'], 'aaa2': ['a2', 'b2', 'c2']}, 'BBB': {'bb1', 'b1']}}

target1 = input_value.keys()
# # dict_keys(['AAA', 'BBB'])

target2 = input_value.values()
# # dict_values([{'aaa1': ['a1', 'b1', 'c1'], 'aaa2': ['a2', 'b2', 'c2']}, {'bbb1': ['b1', 'B2']}])

## a desired result
## ## result = {'AAA':['aaa1','aaa2']}

I'd like to take out only the middle key values of AAA's values, aaa1 and aaa2, is there a way (like the result above)?
The method I tried was to extract the key value from target2 (aaa1, aaa2) and change this value to value, but because target2 value is the dict_values value, I couldn't select the key.
I'd appreciate your help.

python dictionary key value

2022-09-21 19:34

2 Answers

// Enter your code here
input_value =  {'AAA': {'aaa1': ['a1', 'b1', 'c1'], 'aaa2': ['a2', 'b2', 'c2']}, 'BBB': {'bbb1': ['b1','b2']}}

// Generate Top Keys as a List
key_list = list(input_value.keys())

result = dict()
for i in range(len(key_list)):
    value = input_value.get(key_list[i]) // get the value of the parent key
    second_key_list = list(value.keys()) // Generate subkeys as a list
    result[key_list[i] = second_key_list // Generate in the form of a result

print('result : ', result)

I created the code intuitively, so please think about it according to your intention and correct it


2022-09-21 19:34

>>> o, *_ = input_value.items() #You can do the first element o = input_value.get(0).
>>> {o[0]:list(o[1].keys())}    # O is a tuple, followed by key and value.
{'AAA': ['aaa1', 'aaa2']}


2022-09-21 19:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.