Python - 我需要这个键,在for循环之外访问的值。我怎样才能使这个全球化

时间:2022-03-09 08:54:36

Here's my sample code : for key,value in application_list.items(): where application_list is a JSON. I need this key and value, later outside of the scope of for loop like this:

这是我的示例代码:for application,application_list.items()中的值:其中application_list是JSON。我需要这个键和值,稍后在for循环范围之外,如下所示:

for key,value in application_list.items():
  .....
  ......
  more computations
dt = datetime.fromtimestamp(int(key))

How can i achieve this ?

我怎样才能做到这一点?

1 个解决方案

#1


0  

If there is a specific key you want to store for later use, simply assign to a variable, e.g. x, as below:

如果您要存储特定密钥供以后使用,只需指定一个变量,例如: x,如下:

for key, value in application_list.items():

    # computations

    x = key  # for your chosen key dependent on your conditions

dt = datetime.fromtimestamp(int(x))

If you want to save the first key only:

如果您只想保存第一个键:

for idx, (key, value) in enumerate(application_list.items(), 1):

    # computations

    if idx == 1:
        x = key  # for your chosen key dependent on your conditions

dt = datetime.fromtimestamp(int(x))

#1


0  

If there is a specific key you want to store for later use, simply assign to a variable, e.g. x, as below:

如果您要存储特定密钥供以后使用,只需指定一个变量,例如: x,如下:

for key, value in application_list.items():

    # computations

    x = key  # for your chosen key dependent on your conditions

dt = datetime.fromtimestamp(int(x))

If you want to save the first key only:

如果您只想保存第一个键:

for idx, (key, value) in enumerate(application_list.items(), 1):

    # computations

    if idx == 1:
        x = key  # for your chosen key dependent on your conditions

dt = datetime.fromtimestamp(int(x))