将列表分配给字典键

时间:2020-05-13 11:03:38

标签: python python-3.x list dictionary

我有4个列表:

list1 = ["in", "france", "germany"]
list2 = ["NAMASTE", "VANAKAM"]
list3 = ["fr1", "fr2", "fr3"]
list4 = ["gem1", "gem2", "gem3", "gem4"]

我希望输出为:

[{'in': ["NAMASTE", "VANAKAM"], 'france': ["fr1", "fr2", "fr3"], 'germany': ["gem1", "gem2", "gem3", "gem4"]}]

无法确定执行此操作的方式。

我只能尝试的是:

Lang = {}
counter = 1
for i in list1:
    counter += 1
    Lang[i] = f'list{counter}'
a = []
a.append(Lang)
print(a)

但是我得到了:

[{'in': 'list2', 'france': 'list3', 'germany': 'list4'}]

如何在此处将具有相同变量名的字符串转换为该变量,以便获得该变量的值?

或通过其他任何方式来获得所需的输出?

4 个答案:

答案 0 :(得分:3)

最简单的方法是:

[dict(zip(list1, [list2, list3, list4]))]

正确执行代码的方法是(尽管我建议您使用上面的代码):

lang = {}
for i, e in enumerate(list1):
    lang[e] = eval(f'list{i + 2}')
a = [lang]
print(a)

请参阅:How to get the value of a variable given its name in a string?

答案 1 :(得分:1)

代替

list1 = ["in", "france", "germany"]
list2 = ["NAMASTE", "VANAKAM"]
list3 = ["fr1", "fr2", "fr3"]
list4 = ["gem1", "gem2", "gem3", "gem4"]

考虑使用列表列表:

country_keys = ["in", "france", "germany"]
country_values = [
    ["NAMASTE", "VANAKAM"],
    ["fr1", "fr2", "fr3"],
    ["gem1", "gem2", "gem3", "gem4"],
]

现在您可以使用zip

lang = dict(zip(country_keys, country_values))

答案 2 :(得分:1)

如果您确实要明确“将具有相同变量名的字符串转换为该变量”,则可以编写

Lang[i] = eval(f'list{counter}')

代替Lang[i] = f'list{counter}

但是,使用eval被认为是非常糟糕的做法。一些更干净的解决方案已发布在其他答案中。考虑阅读以下材料:

Why is using 'eval' a bad practice?

https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

答案 3 :(得分:1)

尝试列表理解:

library(shiny)
library(shinyjs)
library(survival)
library(tidyverse)
library(riskRegression)
library(rms)

ui <- fluidPage(


  useShinyjs(),

  fluidRow(

    column(
      12,
      wellPanel(
        style = "height:150px", 
        sliderInput("n_fjernet", "Lymph Nodal Yield", 
                    min = 4, max = 120, value = 40)
      )
    ),

    fluidRow(align="center", br(), actionButton("do", "Submit"),

             fluidRow(br(),

                      column(12, 

                             uiOutput("test")
                      )
             )
    )
  )
)

server <- function(input, output, session) {

  fit_data <- eventReactive(input$do, {
    p %>% filter(n_fjernet == as.numeric(input$n_fjernet))
  })


  reactive_cali_plot <- eventReactive(input$do, {

    plotCalibration(Score(list(Nomogram=cph(Surv(os.neck,mors)~alder,
                                            data=fit_data(), y=TRUE, x=TRUE)), 
                          Hist(os.neck,mors)~1,
                          data=fit_data(), 
                          plots=c("cal"),
                          times=60, ## This part should be reactively based on input$time_cali from renderUI() in output$test
                          metrics=c("auc","brier")), 
                    cens.method = "local", 
                    legend.x=.6,
                    legend.y=.35,
                    cex=1,
                    brier.in.legend = TRUE,
                    auc.in.legend = TRUE)
  })

  output$cali_plot <- renderPlot({


    reactive_cali_plot()

  })


  observeEvent(input$do, {

    output$test <- renderUI({


      tabsetPanel(id = "something", 
                  tabPanel(title = "Cali plot",
                           sliderInput("time_cali", "Months to predict", 
                                       min = 12, max = 120, value = 60),
                           plotOutput("cali_plot",width = "90%", height="650px"))

      )
    })
  })


}

shinyApp(ui, server)