交换包含词典列表的字典中的值?

时间:2019-09-27 05:54:04

标签: python dictionary

我有一个字典,其中包含以下字典列表。

我想根据名称交换字典列表的所有值。

示例:swap_function('Arvind','Jayesh')应该交换其他值,例如姓,全名和电子邮件。

我已经从其他网站的参考文献中进行了很多尝试,但未能实现我的目标。

data = {
   "items":[
      {                 
         "name":"Arvind",
         "surname":"Patel",
         "fullname":"Arvind Patel",
         "email":"abc@xyx.com"        
      },
      {        
         "name":"Jayesh",
         "surname":"Patel",
         "fullname":"Jayesh Patel",
         "email":"Patel@gmail.com"
      },
      {        
         "name":"Krishna",
         "surname":"dave",
         "fullname":"Krishna dave",
         "email":"Krishna@xyz.com"
      },
      {        
         "name":"Aditya",
         "surname":"Patel",
         "fullname":"Aditya Patel",
         "email":"Aditya@abc.com"
      }

   ]
}

我已经尝试过以下方法,但是之后我就没主意了。

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":"Krishna@xyz.com"        
      },
      {        
         "name":"Jayesh",
         "surname":"Patel",
         "fullname":"Jayesh Patel",
         "email":"Patel@gmail.com"
      },
      {        
         "name":"Krishna",
         "surname":"Patel",
         "fullname":"Arvind Patel",
         "email":"abc@xyx.com"
      },
      {        
         "name":"Aditya",
         "surname":"Patel",
         "fullname":"Aditya Patel",
         "email":"Aditya@abc.com"
      }

   ]
}

3 个答案:

答案 0 :(得分:2)

尝试以下代码:

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'

并给出:

{'items': [{'name': 'Arvind',
   'surname': 'dave',
   'fullname': 'Krishna dave',
   'email': 'Krishna@xyz.com'},
  {'name': 'Jayesh',
   'surname': 'Patel',
   'fullname': 'Jayesh Patel',
   'email': 'Patel@gmail.com'},
  {'name': 'Krishna',
   'surname': 'Patel',
   'fullname': 'Arvind Patel',
   'email': 'abc@xyx.com'},
  {'name': 'Aditya',
   'surname': 'Patel',
   'fullname': 'Aditya Patel',
   'email': 'Aditya@abc.com'}]}

好,现在让我们使用以下功能概括该示例:

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

在这种情况下,您将在此功能中使用:

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

您将获得上面显示的相同结果。

代码解释

swap_dict_list函数接收字典'dict_list'的列表,要搜索的2个值('val1'和'val2')以及在其上执行{{1} }搜索。

该函数查找与要搜索的两个值相对应的索引,如果它们都存在,则执行交换。如果targetblock_target,则不交换目标值。

使用generator expression有效地进行搜索。

答案 1 :(得分:0)

如果我说对了:

首先,您要查找两个字典的索引:

Find the index of a dict within a list, by matching the dict's value

然后切换项目的位置:

How to switch position of two items in a Python list?

def switch(list,name1, name2):
     index1 = next((index for (index, d) in enumerate(list) if d["name"] == name1), None)
     index2 = next((index for (index, d) in enumerate(list) if d["name"] == name2), None)
     list[index1]['name'], list[index2]['name'] = list[index2]['name'], list[index1]['name']
     return list

data['items'] = switch(data['items'], 'Arvind', 'Krishna')

答案 2 :(得分:0)

尝试一下:

def switch(list, name1, name2):
    for item in list:
        if item['name'] == name1:
            item['name'] = name2
        elif item['name'] == name1:
            item['name'] = name2

    return list


data = {
   "items":[
      {
         "name":"Arvind",
         "surname":"Patel",
         "fullname":"Arvind Patel",
         "email":"abc@xyx.com"
      },
      {
         "name":"Jayesh",
         "surname":"Patel",
         "fullname":"Jayesh Patel",
         "email":"Patel@gmail.com"
      },
      {
         "name":"Krishna",
         "surname":"dave",
         "fullname":"Krishna dave",
         "email":"Krishna@xyz.com"
      },
      {
         "name":"Aditya",
         "surname":"Patel",
         "fullname":"Aditya Patel",
         "email":"Aditya@abc.com"
      }

   ]
}

data['items'] = switch(data['items'], 'Arvind', 'Jayesh')

print data