Swap values in dictionary which contain list of dictionaries?

Aditya

I have dictionary which contain list of dictionaries as below.

I want to swap all values of list of dictionary based on name.

Example: swap_function('Arvind','Jayesh') should swap other values like surname, fullname & email.

I have already tried a lot from other website's references but not able achieve my goal.

data = {
   "items":[
      {                 
         "name":"Arvind",
         "surname":"Patel",
         "fullname":"Arvind Patel",
         "email":"[email protected]"        
      },
      {        
         "name":"Jayesh",
         "surname":"Patel",
         "fullname":"Jayesh Patel",
         "email":"[email protected]"
      },
      {        
         "name":"Krishna",
         "surname":"dave",
         "fullname":"Krishna dave",
         "email":"[email protected]"
      },
      {        
         "name":"Aditya",
         "surname":"Patel",
         "fullname":"Aditya Patel",
         "email":"[email protected]"
      }

   ]
}

I have tried like below but after that I am out of ideas.

def name_swap(name1, name2):

   for key, item in data.items():
      first_dict = item[0]
      second_dict = item[1]
      third_dict = item[2]
      forth_dict = item[3]
      fifth_dict = item[4]
after name_swap('Arvind', 'Krishna')

output : 
data = {
   "items":[
      {                 
         "name":"Arvind",
         "surname":"dave",
         "fullname":"Krishna dave",
         "email":"[email protected]"        
      },
      {        
         "name":"Jayesh",
         "surname":"Patel",
         "fullname":"Jayesh Patel",
         "email":"[email protected]"
      },
      {        
         "name":"Krishna",
         "surname":"Patel",
         "fullname":"Arvind Patel",
         "email":"[email protected]"
      },
      {        
         "name":"Aditya",
         "surname":"Patel",
         "fullname":"Aditya Patel",
         "email":"[email protected]"
      }

   ]
}
Massifox

Try this code:

i = next(i for i,item in enumerate(data['items']) if item['name'] == 'Arvind')
j = next(i for i,item in enumerate(data['items']) if item['name'] == 'Krishna')
data['items'][i]['name'], data['items'][j]['name'] = 'Krishna', 'Arvind'

And gives:

{'items': [{'name': 'Arvind',
   'surname': 'dave',
   'fullname': 'Krishna dave',
   'email': '[email protected]'},
  {'name': 'Jayesh',
   'surname': 'Patel',
   'fullname': 'Jayesh Patel',
   'email': '[email protected]'},
  {'name': 'Krishna',
   'surname': 'Patel',
   'fullname': 'Arvind Patel',
   'email': '[email protected]'},
  {'name': 'Aditya',
   'surname': 'Patel',
   'fullname': 'Aditya Patel',
   'email': '[email protected]'}]}

Ok now let's generalize this example, with the following function:

def swap_dict_list(dict_list, val1, val2, target='name', block_target=True):   
    try:
        i = next(i for i,item in enumerate(dict_list) if item[target] == val1)
        j = next(i for i,item in enumerate(dict_list) if item[target] == val2)
    except StopIteration:
        return dict_list
    dict_list[i], dict_list[j] = dict_list[j], dict_list[i]
    if block_target:
        dict_list[i][target], dict_list[j][target] = val1, val2
    return dict_list

In your case, you will use the function in this:

data['items'] = swap_dict_list(data['items'], 'Arvind', 'Krishna', target='name', block_target=True)

And you will get the same result shown above.

Code explenation

The swap_dict_list function receives as input the list of dictionaries 'dict_list', the 2 values ​​to search ('val1' and 'val2') and the dictionary key on which to perform the target search.

The function finds the indexes corresponding to the two values ​​searched for, and if they both exist it performs the swap. If block_target is True, the target values ​​are not exchanged.

The search is effected efficiently using generator expression.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Swap keys for values in dictionary?

Converting a dictionary of dictionaries to a List of dictionaries

Converting a dictionary with values as list of dictionaries into pandas DataFrame

Summing values in dictionary of dictionaries

Generating a list of dictionaries in python using lists that contain duplicate values

All dictionaries in a list change their values when the dictionary changes

Print dictionary values linked to keys which are in a list

Iterating over dictionary values which are lists to create a new list of dictionaries

How to modify the values of a dictionary from a list of dictionaries

List all keys in dictionaries which are inside a list. (Dictionary in a list)

Split list values inside dictionary to separate dictionaries

Ansible filter a list of dictionaries to only contain unique values in one field

How to sort a dictionary by values which contain lists in python

How to use Lambda to merge two Dictionary with List<string> contain in Dictionaries

how to print dictionary values in a list of dictionaries?

Sort Dictionary which contains list of dictionaries by value

How to access the last element in the list values in a dictionary that contain lists as values

How to sort dictionaries and create a dictionaries based on the values in the list inside the dictionary

How to convert a list of dictionaries, within a dictionary, to a list of just values?

dictionary of values/lists to list of dictionaries

Swap pandas dataframe having dictionaries with key and list of values

Concatenate values of dictionary of list with nested dictionaries

trying to delete duplicate dictionary values from the list of dictionaries

Updating dictionary values based on another list of dictionaries

change dictionary values to dictionaries from list of dictionaries in python

How to get values from a list of dictionaries, which themselves contain lists of dictionaries in Python

Extracting values of a dictionary which is in a list

How to sort a list of dictionaries by a list that might contain duplicate values?

How to sort a list of dictionaries by a list that can contain duplicate values?