简体   繁体   English

正确访问嵌套 Python 字典的问题

[英]Problem with accessing a nested Python dictionary correctly

I've created a test dictionary, as I'm just learning Python and have stumbled when dealing with the intricacies of dictionaries.我创建了一个测试字典,因为我刚刚学习 Python 并且在处理复杂的字典时遇到了困难。 I've made my code to print-out the 'Id', 'Artist', and 'Album'(s) but I'm not sure why it's printing out twice and incorrectly.: Also, I don't want dictionary format for the 'Albums'.我已经编写了代码来打印“Id”、“Artist”和“Album”(s),但我不确定为什么它会打印两次并且不正确。:另外,我不想要字典格式对于“专辑”。 I only want plain text output.我只想要纯文本输出。 Is it that my dictionary structured wrong?是不是我的字典结构不对? I'm uncertain of the way I extract the information basically.我不确定我基本上提取信息的方式。

    my_dict = {0: {"Artist": "Pat Metheny", "Album": {"Offramp", "First Circle"}},
               1: {"Artist": "William Ackerman", "Album": {"Imaginary Roads", "Passage"}},
               2: {"Artist": "John Coltrane", "Album": {"A Love Supreme", "Ballads"}}}


    for id, Artist in my_dict.items():
    print("Id:", id)
        for name, Album_name in Artist.items():
            print("Artist: {0}\nAlbums: {1}".format(Artist[name], Album_name))

The output gives:输出给出:

    Id: 0
    Artist: Pat Metheny
    Albums: Pat Metheny
    Artist: {'First Circle', 'Offramp'}
    Albums: {'First Circle', 'Offramp'}
    Id: 1
    Artist: William Ackerman
    Albums: William Ackerman
    Artist: {'Passage', 'Imaginary Roads'}
    Albums: {'Passage', 'Imaginary Roads'}
    Id: 2
    Artist: John Coltrane
    Albums: John Coltrane
    Artist: {'Ballads', 'A Love Supreme'}
    Albums: {'Ballads', 'A Love Supreme'}

    Process finished with exit code 0

I've used a function to update this dictionary.我使用了一个函数来更新这本字典。 It adds the album, 'Blue Train' to John Coltrane.它将专辑“Blue Train”添加到 John Coltrane。

def update_tree(tree, key, value):
    if key in tree:
        tree[key].update(value)
        return True
    for branch in tree.values():
        if update_tree(branch, key, value):
            return True
    return False


update_tree(my_dict, 2, {"Album": {"A Love Supreme", "Ballads", "Blue Train"}})

but is there any easier way to append an album instead of rewriting the album list?但是有没有更简单的方法来附加专辑而不是重写专辑列表?

I wanted to add to the dictionary the album's year, but an error came up.我想将专辑的年份添加到字典中,但出现错误。 Here's my dictionary:这是我的字典:

my_dict = {
    0: {
        "Artist": "Pat Metheny",
        "Album": {"Offramp", "First Circle"}
    },
    1: {
        "Artist": "William Ackerman",
        "Album": {1: {"Imaginary Roads", {"Year": "1986"}}, 2: {"Passage", {"Year": "1979"}}}
    },
    2: {
        "Artist": "John Coltrane",
        "Album": {"A Love Supreme", "Ballads"}
    }
}

Do I not have the structure correct?我的结构不正确吗?

Inner for-loop should be used to iterate albums:应该使用内部 for 循环来迭代专辑:

my_dict = {
    0: {
        "Artist": "Pat Metheny",
        "Album": {"Offramp", "First Circle"}
    },
    1: {
        "Artist": "William Ackerman",
        "Album": {"Imaginary Roads", "Passage"}
    },
    2: {
        "Artist": "John Coltrane",
        "Album": {"A Love Supreme", "Ballads"}
    }
}


for id_key, artist_value in my_dict.items():
  print(f"ID: {id_key}")
  print(f"Artist: {artist_value['Artist']}")
  print(f"Album: {artist_value['Album']}")

print("\n\nIterate on albums too:\n")

for id_key, artist_value in my_dict.items():
  print(f"ID: {id_key}")
  print(f"Artist: {artist_value['Artist']}")
  print("Albums:")
  for album in artist_value["Album"]:
    print(f"- {album}")

Output:输出:

ID: 0
Artist: Pat Metheny
Album: {'First Circle', 'Offramp'}
ID: 1
Artist: William Ackerman
Album: {'Imaginary Roads', 'Passage'}
ID: 2
Artist: John Coltrane
Album: {'Ballads', 'A Love Supreme'}


Iterate on albums too:

ID: 0
Artist: Pat Metheny
Albums:
- First Circle
- Offramp
ID: 1
Artist: William Ackerman
Albums:
- Imaginary Roads
- Passage
ID: 2
Artist: John Coltrane
Albums:
- Ballads
- A Love Supreme

https://repl.it/@dr3tt/Basics-Dict-Iteration https://repl.it/@dr3tt/Basics-Dict-Iteration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM