简体   繁体   English

遍历字典中单个键的多个值

[英]Iterate over multiple values for a single key in dictionary

one of my dictionary contains multiple values for a single key. 我的词典之一包含单个键的多个值。 I have worked on simple dictionary with single value. 我曾经研究过具有单个值的简单字典。 I am new to python not able to figure out how to handle this. 我是python的新手,无法弄清楚该如何处理。 I need to update a database table where "field" will be the column and the values will be from "rows" as in the below sample. 我需要更新一个数据库表,其中“字段”将是列,而值将来自“行”,如以下示例所示。

"field" key will be the column and "rows" key will be values in database table for corresponding columns. “字段”键将是列,“行”键将是数据库表中对应列的值。

dictn = {
    u'field': [u'time',
               u'met1',
               u'met2',
               u'met3',
               u'met4',
               u'met5',
               u'met6',
               u'met7'],
    u'set': 0,
    u'messages': [{u'text': u'string',
                   u'type': u'INFO'}],
    u'rows': [[u'2016-01-00:00',
               None,
               u'0.24',
               None,
               u'0.24',
               None,
               u'0.16',
               u'60'],
              [u'2016-01-00:01:00:00',
               None,
               u'0.00',
               None,
               u'0.00',
               None,
               u'0.003500',
               u'60'],
              [u'2016-01-00:02:00.00',
               None,
               u'0.64',
               None,
               u'0.64',
               None,
               u'0.26',
               u'60']]
}

You can iterate over list of lists of values ie dictn['rows'] and use every list of values along with list of column names ie dictn['field'] to save all the records to database. 您可以遍历值列表即dictn['rows']列表,并使用每个值列表以及列名列表即dictn['field']来将所有记录保存到数据库。

for value_lst in dictn['rows']:
  record_dict = dict(zip(dictn['field'], value_lst))
  db_model.save(record_dict)

Where db_model.save() takes a dictionary of single database record in the format 其中db_model.save()采用格式为单个数据库记录的字典

{
  u'time': u'2016-01-00:00',
  u'met1': None,
  ... so on for all the fields ...
}

and saves it in the database. 并将其保存在数据库中。

a single key in a dictionary can refer to only a single value 字典中的单个键只能引用单个值

In the example you gave the key u'field' contains a single value which is a list of elements ie 在示例中,您给键u'field'包含一个值,该值是元素列表,即

[u'time',u'met1',u'met2',u'met3',u'met4',u'met5',u'met6',u'met7']

hence in order to access the list stored at key value u'field you should use 因此,为了访问存储在键值u'field的列表,您应该使用

list_of_elements = dictn[u'field']

there after you can iterate across all the elements in the list using a for loop 之后,您可以使用for循环遍历列表中的所有元素

for element in list_of_elements:
    # do something

Hope this link can help you 希望此链接可以为您提供帮助

append multiple values for one key in Python dictionary 在Python字典中为一个键附加多个值

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

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