【问题标题】:Python Changing value in JSON filePython更改JSON文件中的值
【发布时间】:2021-09-06 06:03:13
【问题描述】:

我正在尝试更新 JSON 文件中的演员列表。我正在使用 for 循环来获取演员列表,但是当我尝试使用 if 子句更新列表时,输出没有改变。我想把“Alan Arkin”改成“John Doe”

我现在得到的输出是:"actors": ["Ethan Hawke", "Uma Thurman", "Alan Arkin", "Loren Dean"]

期望的输出是:“actors”:[“Ethan Hawke”、“Uma Thurman”、“John Doe”、“Loren Dean”]

这是“movie_1.txt”文件中的内容

{ “标题”:“加塔卡”, “发布年份”:1997 年, “真棒”:是的, “won_oscar”:假的, “演员”:[“伊桑·霍克”、“乌玛·瑟曼”、“艾伦·阿金”、“洛伦·迪恩”]、 “预算”:空, “学分”:{ “导演”:“安德鲁·尼科尔”, “作家”:“安德鲁·尼科尔”, “作曲家”:“迈克尔·尼曼”, “电影摄影师”:“Slawomir Idziak” } }

我的代码现在的样子。我的问题是带有嵌套 if 子句的 for 循环,该子句获取列表中的名称。遍历列表的 for 循环和 if 子句应该抓取“Alan Arkin”的一个实例并将其更改为“John Doe”

path = 'movie_1.txt'
import json

json_file = open(path, encoding="utf-8")
movie = json.load(json_file)
json_file.close()

print(movie['actors']) # prints unchanged list

for x in movie["actors"]:
   if x == 'Alan Arkin':
     x = 'John Doe'

print(movie['actors']) # prints changed list

【问题讨论】:

    标签: python json


    【解决方案1】:

    字符串在 Python 中是不可变类型,因此重新分配作为字符串的循环变量将无法按预期工作。顺便说一句,已知的可变类型是listdictset。不完全确定,但我猜你正在创建一个新的局部变量 x 并分配给它。该变量仅对每个循环迭代都是本地的,因此实际上不会更新列表。

    下面是一个可行的解决方案,它使用简单的list 推导来构建一个替换所需演员名称的新列表:

    import json
    
    
    movies_json = """
    { "title": "Gattaca", "release_year": 1997, "is_awesome": true, "won_oscar": false, "actors": ["Ethan Hawke", "Uma Thurman", "Alan Arkin", "Loren Dean"], "budget": null, "credits": { "director": "Andrew Niccol", "writer": "Andrew Niccol", "composer": "Michael Nyman", "cinematographer": "Slawomir Idziak" } }
    """
    
    movie = json.loads(movies_json)
    
    print(movie['actors']) # prints unchanged list
    
    # Note the old code:
    # for x in movie["actors"]:
    #    if x == 'Alan Arkin':
    #      x = 'John Doe'
    
    # Do a list comprehension (build a *new* list with the replaced values)
    actor_repls = {'Alan Arkin': 'John Doe'}
    actors = [actor_repls.get(actor, actor) for actor in movie['actors']]
    # You can re-assign it if you want, though it's technically not needed
    # movie['actors'] = actors
    
    print(actors)   # prints changed list
    # prints:
    #   ['Ethan Hawke', 'Uma Thurman', 'John Doe', 'Loren Dean']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 2019-02-18
      • 2021-12-17
      • 2016-03-01
      • 1970-01-01
      • 2018-01-20
      相关资源
      最近更新 更多