将列表值附加到字典键

时间:2016-05-13 19:10:36

标签: python list dictionary

我正在尝试创建一个python脚本,我被这些字典困住了。我已经阅读了其他一些论坛,但似乎无处可去。我是一个非常新的python程序员,所以请温柔。

我想做什么:

1)设置如下字典:{'Name':'userid','jobid:jobid','walltime:walltime,'nodes:nds'}

2)遍历从外部函数调用创建的条目列表并提取信息以填充字典

3)问题:我无法弄清楚如何将条目附加到适当的键

例如,我想要这个:

{‘Name’:’jose’,’jobid’:’001,002,003,005’,’walltime:32:00,240:00,04:00,07:00’,’nodes’:32,32,500’} 

注意一个用户ID,我有多个jobid,walltimes和节点 (len(jobids)==len(walltimes)==len(nodes)适用于任何一个用户ID,但可以因用户ID而异)

我能够让脚本找到每个用户名的第一个值,但它永远不会附加。我如何才能追加这个?

这是我试过的

from collections import defaultdict
pdict = defaultdict(list)

start the loop:

 # get new values – add these to the dictionary keyed 
 # on username (create a new entry or append to existing entry)
    …
    (jobid,userid,jobname, sessid, nds, tsk, walltime,rest)= m.groups()  

    ...
    if userid in pdict:
       print "DEBUG: %s is currently in the dictionary -- appending entries" %(userid)
       pdict[userid][‘jobid’] = pdict[userid][jobid].append(jobid)    I 
     # repeat for nodes, walltime, etc 

    if not userid in pdict:
        print "DEBUG: %s is not in the dictionary creating entry" %(userid)
        pdict[userid] = {}  # define a dictionary within a dictionary with key off userid
        pdict[userid]['jobid'] = jobid
        pdict[userid]['jobname'] = jobname
        pdict[userid]['nodes'] = nds
        pdict[userid]['walltime'] = walltime

我知道这是错的,但无法弄清楚如何让追加工作。我已尝试过本网站提供的许多建议。我需要在键入到用户ID

的循环中附加(到字典)最近的值

以下是输出的示例 - 它不为每个用户标识添加多个条目,而是仅为每个用户标识获取第一个值

  

userid jmreill包含数据:{'nodes':'1','jobname':   'A10012a_ReMig_Q','walltime':'230:0','jobid':'1365582'}

     

userid igorysh包含数据:{'nodes':'20','jobname':   'emvii_Beam_fwi6','walltime':'06:50','jobid':'1398100'}

有什么建议吗?这应该很容易,但我无法理解!

6 个答案:

答案 0 :(得分:1)

SELECT        HHID, MIN(ORDDATE) AS FirstOrdDate
FROM            dbo.Orders
GROUP BY HHID, DOL
HAVING (DOL > 0.00)

答案 1 :(得分:0)

与键'jobid'对应的值应该是字符串列表而不是字符串。如果以这种方式创建字典,则可以通过以下方式将新的jobid附加到列表中:

pdict[userid]['jobid'].append(jobid)

答案 2 :(得分:0)

我无法解释为什么在以下代码中使用lambda表达式的解释,但您必须定义defaultdict的{​​{1}}:

defaultdict

会奏效。

答案 3 :(得分:0)

php bin/magento setup:upgrade –keep-generated php bin/magento setup:static-content:deploy 方法不会返回列表...它会在适当的位置进行修改。此外,您需要将元素初始化为列表(使用方括号):

append()

答案 4 :(得分:0)

append不会返回值,它会修改列表,并且您忘记在equals右边引用'jobid'。因此,您应该将#pragma once #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> typedef struct { float red_; float blue_; float green_; }RGB; struct BMPHeader { // http://en.wikipedia.org/wiki/BMP_file_format char file_type_[2]; // "BM" int file_size_; // Size of file in bytes int reserved_; // set to 0 int offBits_; // Byte offset to actual bitmap data // (= 54) int header_size_; // Size of BITMAPINFOHEADER, // in bytes (= 40) int width_; // Width of image, in pixels int height_; // Height of images, in pixels short planes_; // Number of planes in target device (set to 1) short bit_count_; // Bits per pixel (24 in this case) int compression_; // Type of compression // (0 if no compression) int size_image_; // Image size, in bytes // (0 if no compression) int pixel_per_meter_x_; // Horizontal resolution of the image // (pixel per meter) int pixel_per_meter_y_; // Vertical resolution of the image // (pixel per meter) int num_color_palette_; // Number of colors in the color table // (if 0, use maximum allowed by // biBitCount) int num_color_important_; // Number of important colors. // If 0, all colors are important }; const bool writeBMP24(const char *filename, const int x_res, const int y_res, RGB* rgb_array) { int i, j, ipos; int bytesPerLine; unsigned char *buffer; FILE *file; struct BMPHeader header; int width = x_res; int height = y_res; // The length of each line must be a multiple of 4 bytes bytesPerLine = (3 * (width + 1) / 4) * 4; strcpy(header.file_type_, "BM"); header.offBits_ = 54; header.file_size_ = header.offBits_ + bytesPerLine * height; header.reserved_ = 0; header.header_size_ = 40; header.width_ = width; header.height_ = height; header.planes_ = 1; header.bit_count_ = 24; header.compression_ = 0; header.size_image_ = bytesPerLine * height; header.pixel_per_meter_x_ = 0; header.pixel_per_meter_y_ = 0; header.num_color_palette_ = 0; header.num_color_important_ = 0; file = fopen(filename, "wb"); if (file == NULL) return(0); fwrite(&header.file_type_, 2, 1, file); fwrite(&header.file_size_, 4, 1, file); fwrite(&header.reserved_, 4, 1, file); fwrite(&header.offBits_, 4, 1, file); fwrite(&header.header_size_, 4, 1, file); fwrite(&header.width_, 4, 1, file); fwrite(&header.height_, 4, 1, file); fwrite(&header.planes_, 2, 1, file); fwrite(&header.bit_count_, 2, 1, file); fwrite(&header.compression_, 4, 1, file); fwrite(&header.size_image_, 4, 1, file); fwrite(&header.pixel_per_meter_x_, 4, 1, file); fwrite(&header.pixel_per_meter_y_, 4, 1, file); fwrite(&header.num_color_palette_, 4, 1, file); fwrite(&header.num_color_important_, 4, 1, file); buffer = (unsigned char *)malloc(bytesPerLine); if (buffer == NULL) { fprintf(stderr, "Can't allocate memory for BMP file.\n"); return false; } for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { ipos = 3 * (width * i + j); buffer[3 * j] = (unsigned char)rgb_array[ (j + i * x_res)].blue_; // blue buffer[3 * j + 1] = (unsigned char)rgb_array[ (j + i * x_res)].green_; // green buffer[3 * j + 2] = (unsigned char)rgb_array[ (j + i * x_res)].red_; // red } fwrite(buffer, bytesPerLine, 1, file); } free(buffer); fclose(file); return true; } const bool readBMP24( const char* imagepath, int* res_x_, int* res_y_, RGB** rgb_array) { printf("Reading image %s\n", imagepath); // Data read from the header of the BMP file unsigned char header[54]; unsigned int dataPos; unsigned int imageSize; unsigned int width, height; // Open the file FILE * file = fopen(imagepath, "rb"); if (!file) { printf("%s could not be opened." " Are you in the right directory?" " Don't forget to read the FAQ !\n", imagepath); getchar(); return 0; } // Read the header, i.e. the 54 first bytes // If less than 54 bytes are read, problem if (fread(header, 1, 54, file) != 54) { printf("Not a correct BMP file\n"); return false; } // A BMP files always begins with "BM" if (header[0] != 'B' || header[1] != 'M') { printf("Not a correct BMP file\n"); return false; } // Make sure this is a 24bpp file if (*(int*)&(header[0x1E]) != 0) { printf("Not a correct BMP file\n"); return false; } if (*(int*)&(header[0x1C]) != 24) { printf("Not a correct BMP file\n"); return false; } // Read the information about the image dataPos = *(int*)&(header[0x0A]); imageSize = *(int*)&(header[0x22]); width = *(int*)&(header[0x12]); height = *(int*)&(header[0x16]); // Some BMP files are mis-formatted, guess missing information // if (imageSize == 0) imageSize = width*height*3; // 3 : one byte for each Red, Green and Blue component if (dataPos == 0) dataPos = 54; // The BMP header is done that way *res_x_ = width; *res_y_ = height; int scanline_byte = *res_x_ * 3; int padding = 0; while ((scanline_byte + padding) % 4 != 0) padding++; int psb = scanline_byte + padding; // padded scanline byte imageSize = psb*height; // Read the actual data from the file into the buffer unsigned char* image_buf = (unsigned char*)malloc( sizeof(unsigned char)*imageSize); fread(image_buf, 1, imageSize, file); // Create a buffer // data_.initialize(0, 0, width, height, false); *rgb_array = (RGB*)malloc(sizeof(RGB)*(width * height )); long buf_pos = 0; long new_pos = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < 3 * width; x += 3) { new_pos = y*width + x / 3; buf_pos = y*psb + x; (*rgb_array)[new_pos].red_ = (float)image_buf[buf_pos + 2]; (*rgb_array)[new_pos ].green_ = (float)image_buf[buf_pos + 1]; (*rgb_array)[new_pos].blue_ = (float)image_buf[buf_pos + 0]; } } // Everything is in memory now, the file wan be closed fclose(file); free(image_buf); return true; } 替换为pdict[userid][‘jobid’] = pdict[userid][jobid].append(jobid)。另请考虑@Jasper的评论。

答案 5 :(得分:0)

你正在寻找一个dicts的词典? AutoVivification是完美的解决方案。在Python中实现perl的自动修复功能。

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value​

这使一切变得更容易。请注意,pdict[userid]['jobid']的值应为列表[jobid],而不是变量jobid,因为您有多个jobid

pdict = AutoVivification()

if userid in pdict:
    pdict[userid]['jobid'].append(jobid) 
else:
    pdict[userid]['jobid'] = [jobid] # a list

请参阅What is the best way to implement nested dictionaries in Python?