Python迭代多值嵌套字典

时间:2017-06-20 07:39:52

标签: python dictionary

我有以下数据结构调用letters_dict:

var updateBlocked = false;
function worker() {
    if (updateBlocked) return;
    // your code to fetch new info
}

setInterval(worker, 3000);

function onSomeEvent() {
    updateBlocked = true;
    setTimeout(function(){updateBlocked = false;}, 20000);
}

我想迭代外部字典的每个项目,然后是内部值,价格数量和时间,然后是价格数量和时间内的每个值,然后进行数据处理。这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:0)

首先使用key_level1和val_level1迭代外部值,然后使用key_level2,val_level2迭代内部值:

> df=NULL
> df$ID=sample(38700:38800,10,F)
> df$test1=sample(15:25,10,F)
> df$test2=sample(15:35,10,F)
> df=as.data.frame(df)
> df
      ID test1 test2
1  38784    24    19
2  38747    15    15
3  38791    16    34
4  38721    25    32
5  38769    20    23
6  38706    21    26
7  38702    17    29
8  38761    22    28
9  38763    19    25
10 38740    23    16
> df$ran=sample(2,nrow(df),T)
> df$test=ifelse(df$ran==1,df$test1,df$test2)
> df
      ID test1 test2 ran test
1  38784    24    19   1   24
2  38747    15    15   1   15
3  38791    16    34   1   16
4  38721    25    32   1   25
5  38769    20    23   1   20
6  38706    21    26   1   21
7  38702    17    29   2   29
8  38761    22    28   1   22
9  38763    19    25   1   19
10 38740    23    16   2   16
> df$testchosen=ifelse(df$ran==1,"test1","test2")
> df
      ID test1 test2 ran test testchosen
1  38784    24    19   1   24      test1
2  38747    15    15   1   15      test1
3  38791    16    34   1   16      test1
4  38721    25    32   1   25      test1
5  38769    20    23   1   20      test1
6  38706    21    26   1   21      test1
7  38702    17    29   2   29      test2
8  38761    22    28   1   22      test1
9  38763    19    25   1   19      test1
10 38740    23    16   2   16      test2
> 

答案 1 :(得分:0)

for key_1 in letters_dict:
    for key_2 in letters_dict[key_1]:
        for value in letters_dict[key_1][key_2].split(','):

这对我来说是最简单的方式(并不意味着最好的方式)。 我不确定你为什么甚至不尝试......

相关问题