How can i extract the values from existing list-dictionary to create a new dictionary?

Question:

how do i extract the values from the existing list-dictionary in a python to create a new dictionary as shown below ..any help will be appreciated

old_list_dict=[{'A':'FRUITS','B':'APPLE'} , {'A':'FRUITS','B':'BANANA'} ,{'A':'FRUITS','B':'PECAN'}]


new_dict={'FRUITS':'APPLE','FRUITS':'BANANA','FRUITS':'PECAN'}

Or 

new_dict ={'FRUITS':{'APPLE','BANANA','PECAN'}


Asked By: shirop

||

Answers:

Try this

new_dictionary = {
    existing_dictionary["current"]: existing_dictionary["area"]
}
Answered By: Eureka

Assuming all your dictionaries have exactly two items, you can use map to extract values in pairs for the dictionary constructor:

old_list_dict=[{'A':'APPLE','B':'FRUITS'} ,
               {'A':'Banana','B':'FRUITS'} ,
               {'A':'PECAN','B':'FRUITS'}]

new_dict = dict( map(dict.values,old_list_dict) )

print(new_dict)
                                                                          
{'APPLE': 'FRUITS', 'Banana': 'FRUITS', 'PECAN': 'FRUITS'}

Note that, if you have duplicate ‘A’ values in the list (ex: ‘PECAN’ multiple times, you will only get one of them in the new dictionary

For the second form, using update() will allow the values to be accumulated in a set for each key:

new_dict = dict()
new_dict.update( (k,new_dict.get(k,set())|{v})
                 for (v,k) in map(dict.values,old_list_dict)) 
print(new_dict)

{'FRUITS': {'Banana', 'PECAN', 'APPLE'}} 

In this case the .update() method will receive tuples containing a key and a set() value to be added or updated in new_dict.

These tuples will be build from the pairing of values from the old_lit_dict list as (v,k). For example (‘APPLE’,’FRUITS’).

But, since we want the final values to be sets, accumulated for the ‘FRUITS’ key, the actual tuple produced for the update reads the existing key new_dict.get(k,set()) to get its set of values and adds the current value to it | {v} (the | is a union operator with the single value set {v}).

The ,set()) part of the get method ensures that an initial (empty) set is returned when the key is not yet present in the new_dict (e.g. the first time we encounter ‘FRUITS’)

The comprehension in this example is functionally equivalent to a more traditional for loop:

new_dict = dict()
for D in old_list_dict:
   v,k = D.values()           # extract value and key (e.g. APPLE,FRUITS)
   if k not in new_dict:      # assign empty set to key if it is new
       new_dict[k] = set()
   new_dict[k].add(v)         # add value to key's set 
Answered By: Alain T.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.