如何隔离python字典中的一个特定键。

时间:2017-07-22 01:03:31

标签: python dictionary

我需要从很多视频文件中读取一些元数据。经过一些研究后,我碰到了http://www.scikit-video.org。我使用了skvideo.io.ffprobe,它给了我想要的结果。它返回一个字典,其中包含我正在寻找的信息。

看起来像这样:

{ "@index": "0", "@codec_name": "mjpeg", "@nb_frames": "2880", "disposition": {"@default": "1", "@dub": "0", "@timed_thumbnails": "0"}, "tag": [{"@key": "creation_time", "@value": "2006-11-22T23:10:06.000000Z"}, {"@key": "language", "@value": "eng"}, {"@key": "encoder", "@value": "Photo - JPEG"}]}

或者打印漂亮:

{
    "@index": "0", 
    "@codec_name": "mjpeg", 
    "@nb_frames": "2880", 
    "disposition": {
        "@default": "1", 
        "@dub": "0", 
        "@timed_thumbnails": "0"
    }, 
    "tag": [
        {
            "@key": "creation_time", 
            "@value": "2006-11-22T23:10:06.000000Z"
        }, 
        {
            "@key": "language", 
            "@value": "eng"
        }, 
        {
            "@key": "encoder", 
            "@value": "Photo - JPEG"
        }
    ]
}

我的问题是如何隔离日期“2006-11-22T23:10:06.000000Z”。我尝试了一些不同的东西,但我卡住了。我无法得到钥匙或价值观。我相信我错过了一些东西。

我非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:1)

您有一个列表作为键"tag"的值,因此要访问它,您需要从列表中获取列表。

your_dict = #The code you're using to get that dictionary
internal_list = your_dict["tag"]
correct_dict = internal_list[0] #Because it's at the first position of the list
print(correct_dict["@value"]) #This prints the value of that dictionary from within the list at value of key "tag"

或者您可以一步完成所有操作

your_dict = #The code you're using to get that dictionary
print(your_dict["tag"][0]["@value"])

答案 1 :(得分:1)

在没有任何假设标签列表的第一个元素包含创建时间的情况下,您可能会发现 where creation_time被指定...

data = {"@index": "0", "@codec_name": "mjpeg", "@nb_frames": "2880", "disposition": {"@default": "1", "@dub": "0", "@timed_thumbnails": "0"},
        "tag": [{"@key": "creation_time", "@value": "2006-11-22T23:10:06.000000Z"}, {"@key": "language", "@value": "eng"}, {"@key": "encoder", "@value": "Photo - JPEG"}]}

def get_creation_time(data):
    for inner_dict in data["tag"]:
        if inner_dict['@key'] == 'creation_time':
            return inner_dict['@value']
    raise ValueError('creation_time key value is not in tag information')

这也假设标签中的每个“内部字典”都包含@key和@value。