【问题标题】:Iterate through a Python Dictionary and delete a particular element if matches a specific string遍历 Python 字典并在匹配特定字符串时删除特定元素
【发布时间】:2021-10-02 10:24:54
【问题描述】:

我有一本字典,比如-

mydict = {
           'users':
              [
                {
                  'userid': 'u1234'
                  'name': 'user1'
                },
                {
                  'userid': 'u0007'
                  'name': 'user2'
                }                 
              ]
            }

我想要一个功能,如果我传递 userid=u1234,它应该遍历字典并从字典中删除该用户 ID 的详细信息,然后将输出写入文件。

【问题讨论】:

标签: python list python-2.7 dictionary


【解决方案1】:

试试下面的代码:-

for i,v in mydict.items():
    for a in v:
        if (a['userid'] == 'u1234'):
            v.remove(a)

然后使用以下代码写入文件:-

import json
with open('result.json', 'w') as fp:
    json.dump(mydict, fp)

【讨论】:

  • 太棒了,感谢您的及时回复。它就像一个魅力。
【解决方案2】:

此代码将处理您删除特定用户的请求:

for user in mydict['users']:
    if user['userid'] == 'u1234':
        mydict['users'].remove(user)

【讨论】:

    【解决方案3】:

    我会简化:

    user_list = myDict['users']
    for usr_dict in user_list:
      if usr_dict['name'] = name_to_remove:
        myDict['users'].remove(usr_dict)
    

    此外,缩小一步以提高查找效率(和循环简单性),您可以 [重新] 构造您的 myDict,如下所示:

    users_dict = {
           'u1234': {
                  'userid': 'u1234'
                  'name': 'user1'
            },
            'u0007': {
                  'userid': 'u0007'
                  'name': 'user2'
            }
    }
    

    那么你的循环可能变成:

    for uid, obj in users_dict.items():
      if obj['name'] == username_to_delete:
        users_dict.remove(uid)
    

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多