理解复杂词典

2024-09-29 21:48:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python是完全陌生的,并且一直在研究一些需要阅读一些类似这样的复杂字典的东西。你知道吗

var_data:
{
     'pvc' : {
         'files' : ['logs1.txt', 'logs2.txt']
         'version' : 'v192.2'
     },
     'mci' : {
         'files' : ['ld33r3.txt', 'rkkk3k3.txt']
         'version' : 'v39.2'
     },
     'dac' : {
         'files' : ['33.txt', 'logfile3.txt']
         'version' : 'v32.2'
     }
}

我绞尽脑汁想弄明白这是怎么回事。 基本上,我的代码应该能够有一个if条件,它将查看这些数据并根据上面的值为“文件”执行特定的条件语句。。 例如 'dac':{

非常感谢您的指导。。。你知道吗

干杯 卡比尔


Tags: txtdata字典versionvarfiles条件dac
3条回答

听起来像是在问如何从字典中提取键值对。iteritems()可能是语法上最紧凑的方法。举个例子:

var_data = {
    'pvc': {
        'files': ['logs1.txt', 'logs2.txt'],
        'version': 'v192.2'
    },
    'mci': {
        'files': ['ld33r3.txt', 'rkkk3k3.txt'],
        'version': 'v39.2'
    },
    'dac': {
        'files': ['33.txt', 'logfile3.txt'],
        'version': 'v32.2'
    }
}

for filetype, data in var_data.iteritems():
    for filename in data['files']:
        print 'Processing {} as type {}'.format(filename, filetype)

不确定,除非你用我在评论中写的内容更新你的问题,我想这就是你想要的?:-

def process_files(files):
"""
Do some processing on a list of files,
specified by their names
"""

    for file_name in files:
        with open(file_name, 'r+') as file:  # Will work if script in same dir as the files. Else, make the absolute path to file using file_name, and put that instead of just file_name
            file_content = file.read()
            # Do whatever else.
            # Perhaps, read the documentation examples
            # first, get a feeling, then come back


for key in var_data:  # For each key in your dict, (iteration happening here)
    if key == 'pvc':
        # do something on var_data[key]
        files = var_data[key]['files']  # Get your list ['file1.txt', ..]
        process_files(files)   # process this list of files in some func.
    elif key == 'mci':
        # do something else
    elif key == 'dac':
        # and so on.

而且,你的字典结构不好。在files键值的末尾缺少逗号。而var_data:是错误的。你知道吗

I am beating my head around to understand how this reference is.

您有一个包含3个字典的字典,每个字典包含一个字符串列表和一个字符串。你知道吗

my code should be able to have a if condition that will look at this data and do specific conditinal statements for the "files" depending on the value above it.. e.g 'dac'

你可以在上面循环:

for k, v in var_data.iteritems():
  if k == 'pvc':
    # do stuff. Your files list is in v['files']
  elif k == 'mci':
    # do other stuff
  elif k == 'dac':
    # do other stuff

相关问题 更多 >

    热门问题