修改包含元组的字典

时间:2018-11-29 17:50:57

标签: python python-3.x

我正在尝试转换: 此Diciotonary:

dictio = {(3, 3): 'blue'}

dictio = {33: 'blue'}

我毫不费力地修改dict值,但是元组键是问题所在。

看到元组不能被修改,我应该怎么做?

4 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

dictio = {int(''.join(map(str, k))): v for k,v in dictio.items()}

返回:

{33: 'blue'}

这也适用于以下示例:

dictio = {(3, 3): 'blue', (4, 2): 'red', (6, 2, 5): 'green'}

返回:

{33: 'blue', 42: 'red', 625: 'green'}

请注意,如果遇到{(4, 31): 'red', (43, 1): 'green'}之类的情况,这将导致键冲突,并且结果将包括最后一个键值对,在这种情况下为{431: 'green'}

在这种情况下,我会改用以下内容:

dictio = {(3, 3): 'blue', (4, 2): 'yellow', (4, 31): 'red', (43, 1): 'green'}

new_dict = {}
for k,v in dictio.items():
    key = int(''.join(map(str, k)))
    if key in new_dict:
        new_dict[key].append(v)
    else:
        new_dict[key] = [v]

返回:

{33: ['blue'], 42: ['yellow'], 431: ['red', 'green']}

答案 1 :(得分:0)

只需读出第一个字典的键,使用0和1索引分别格式化元组值,然后将这些值和值分配给新字典即可。

可以与dictio作为一行来完成...

dictio = {(3,3):"blue", (5,5):"red"}   

然后...

newDict = {int("{}{}".format(x[0],x[1])):v for x,v in dictio.items()}  

返回...

>>>{33: 'blue', 55: 'red'}  

之所以起作用,是因为我们说“ dictio.items()”包含键:值对,可以分别称为X和V。 NewDict应该由键的第一部分(x [0])组成,其格式与键的第二部分(x [1])相邻,并与先前的不变值配对。

答案 2 :(得分:0)

这是解决您问题的一般方法:

dictio = {(3, 3): 'blue'}


dictio = {int("".join([str(e) for e in key])): dictio[key] for key in dictio.keys()}

输出:

>>> dictio
{33: 'blue'}

答案 3 :(得分:0)

您可以使用一种算法将元组转换为整数:

    void TurnOnLed(ModemState state) {
    LEDState[state] = 1;
}

void TurnOffLed(ModemState state) {
    LEDState[state] = 0;
}

unsigned char CheckLedState(unsigned char state) {
    return LEDState[state];
}
void GetLedStateVar(LEDStateVar *pLS) {
    unsigned char state = pLS->State;
    pLS->LongflashCode = INVALID_VAL;
    switch(state) {
          case ModemTurnOn:
              pLS->LED = Blue;
              pLS->OnTimer  = TimersForBlueLedOn[state];
              pLS->OffTimer = TimersForBlueLedOff[state];
              break;
          case ModemInit:
              pLS->LED = Blue;
              pLS->OnTimer  = TimersForBlueLedOn[state];
              pLS->OffTimer = TimersForBlueLedOff[state];
              break;
          case GSMConnected:
              pLS->LED = Blue;
              pLS->OnTimer  = TimersForBlueLedOn[state];
              pLS->OffTimer = TimersForBlueLedOff[state];
              break;
          case GPRSOn:
              pLS->LED = Blue;
              pLS->OnTimer  = TimersForBlueLedOn[state];
              pLS->OffTimer = TimersForBlueLedOff[state];
              break;
         case ServerNotConnected:
              pLS->LED = Green;
              pLS->OnTimer = TimersForGreenLedOn[state];
              pLS->OffTimer = TimersForGreenLedOff[state];
              break;
         case SwUpdateDownload:
              pLS->LED = Blue;
              pLS->OnTimer = TimersForBlueLedOn[state];
              pLS->OffTimer = TimersForBlueLedOff[state];
              break;
         case SwUpdateRestart:
              pLS->LED = Blue;
              pLS->OnTimer = TimersForBlueLedOn[state];
              pLS->OffTimer = TimersForBlueLedOff[state];
              break;
         case SwUpdateNewVersion:
              pLS->LED = Blue;
              pLS->OnTimer = TimersForBlueLedOn[state];
              pLS->OffTimer = TimersForBlueLedOff[state];
              break;
}

void FlashBlueLed(LEDStateVar *pLSV) {

    if(pLSV->OnTimer == 1) {
              SetLEDBlue(1);          
      }else  {

          if(GetElapsedTime(&BlueFlashTimer) >  pLSV->OnTimer * MILLI_SECONDS) {
             if(!GetLEDBlue()) {
                 SetLEDBlue(1);
                 StartTimer(&BlueFlashTimer);
             }
          }

          if(GetElapsedTime(&BlueFlashTimer) > pLSV->OffTimer * MILLI_SECONDS) {
            if(GetLEDBlue()) {
                SetLEDBlue(0);
                StartTimer(&BlueFlashTimer);
             }
          }
    }
}   

 for(unsigned char i=0; i< FLASHSTATES; ++i) {
      LF.State = i;
      GetLedStateVar(&LF);

      //Flashcode not complete but the state has been reset
      if(i == LastBlueState || i == LastGreenState) {
          if(LF.LED == Blue) {  // BLUE LED
              FlashBlueLed(&LF);

          }else if(LF.LED == Green) {
              FlashGreenLed(&LF);
          }
      } else if(CheckLedState(i) && LF.OnTimer) {

          if(LF.LED == Blue) {  // BLUE LED
              if(LastBlueState == INVALID_VAL) {
                  FlashBlueLed(&LF);
              }
          } else if(LF.LED == Green) {  // GREEN LED
              if(LastGreenState == INVALID_VAL) {
                  FlashGreenLed(&LF);
              }
          } else if(LF.LED == Both) { //BOTH GREEN AND BLUE LED
              FlashBothLeds(&LF);
          }
      }
    }

或者,如果您的元组的大小始终为2,则可以将f字符串与dictio = {(3, 3): 'blue'} dictio = {sum(j*10**i for i, j in enumerate(k)): v for k, v in dictio.items()} print(dictio) {33: 'blue'} 一起使用:

int

当然,您应该注意,两种算法都不会发生冲突:第一种算法会因dictio = {int(f'{k[0]}{k[1]}'): v for k, v in dictio.items()} (1, 0)而失败。后者将在(0, 10)(12, 3)之间失败。如果发生冲突,则不清楚您需要什么。