简体   繁体   English

如何在Python的yaml文件中配置多个字典键?

[英]How do I configure multiple dictionary keys in a yaml file in Python?

I am trying to use a yaml file to store dictionary keys so I can parse various json payloads. 我正在尝试使用yaml文件存储字典键,以便我可以解析各种json负载。

I have the following yaml file loaded into a variable called 'cfg': 我将以下yaml文件加载到名为“ cfg”的变量中:

my_table: metadata

When I run: 当我跑步时:

for i in json['resources']:
    print(i[cfg['my_table']])

I can see all values from my json's ['metadata'] keys just fine. 我可以从json的['metadata']键中看到所有值。

However, I would like to see all values from the ['metadata']['guid'] keys that exist under ['resources']. 但是,我想从['resources']下的['metadata'] ['guid']键中查看所有值。 So when I change my yaml file to: 因此,当我将yaml文件更改为:

my_table: metadata, guid

It doesn't work. 没用 I've also tried these variations: 我还尝试了以下变体:

my_table: ['metadata', 'guid']  #tried ''.join("['{0}']".format(a) for a in cfg['my_table']) which gives me what I want, but when I shove this inside i[], I get a key error
my_table: ['metadata']['guid']  #yaml file doesn't parse properly

Any ideas? 有任何想法吗?

So you want to store dictionary keys in a yaml file? 因此,您要将字典关键字存储在yaml文件中吗?

Just do 做就是了

# keys.yaml
my_table: [metadata, guid]

And then in your python file 然后在你的python文件中

keys = yaml.safe_load('keys.yaml')['my_table']

for obj in json['resources']:  # don't call it json, that's a package name
    print(obj[keys[0]][keys[1]])

For a variable number of keys (not only two) do it like so: 对于可变数量的键(不仅是两个),请按照以下步骤操作:

def recursive_getitem(obj, keys):
   if len(keys) == 0:
      return obj
   return recursive_getitem(obj[keys[0]], keys[1:])

and then do 然后做

for obj in json['resources']:  
    print(recursive_getitem(obj, keys))

To answer your second question in the comments, you need to use a nested list 要回答评论中的第二个问题,您需要使用嵌套列表

# keys.yaml
my_table:
    - [metadata, guid]
    - [entity, name]

.

# py file
keys = yaml.safe_load('keys.yaml')['my_table']

for obj in json['resources']:  # don't call it json, that's a package name
    print(obj[keys[0][0]][keys[0][1]])
    print(obj[keys[1][0]][keys[1][1]])

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

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