python - 将列表值附加到字典键

标签 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,我有多个作业 ID、挂机时间和节点。
(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

我知道这是错误的,但不知道如何让追加工作。我已经尝试过该网站上提供的许多建议。我需要将循环中键入到 userid 的最新值附加(到字典中)

这是一个输出示例 - 它不会为每个用户 ID 附加多个条目,而是仅获取每个用户 ID 的第一个值

userid jmreill contains data: {'nodes': '1', 'jobname': 'A10012a_ReMig_Q', 'walltime': '230:0', 'jobid': '1365582'}

userid igorysh contains data: {'nodes': '20', 'jobname': 'emvii_Beam_fwi6', 'walltime': '06:50', 'jobid': '1398100'}

有什么建议吗?这应该很容易,但我不明白!

最佳答案

from collections import defaultdict

pdict = defaultdict(dict)

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].append(jobid)
     # repeat for nodes, walltime, etc 

    if userid not in pdict:
        print "DEBUG: %s is not in the dictionary creating entry" %(userid)
        pdict[userid]['jobid'] = [jobid]
        pdict[userid]['jobname'] = jobname
        pdict[userid]['nodes'] = nds
        pdict[userid]['walltime'] = walltime

关于python - 将列表值附加到字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217652/

相关文章:

python - 将变量增加到最大大小

python - 使用 python 3.4 使用正则表达式获取多个关键字

list - 最左边-最里面和最外面(Haskell)

python - 使用 "list.extend"时“int”对象不可迭代

.net - 在绑定(bind)到字典的组合框中设置所选项目

行向量矩阵之间的python numpy欧几里得距离计算

Python 2.7 Anaconda Pandas 错误(Ubuntu 14.04)

django - 遍历自定义模板标签传递的列表

c++ - 检查 std::map 的迭代器是否指向倒数第二个元素

c# - 在 C# 中循环字典