python从字符串中获取键值

python从字符串中获取键值,python,json,python-3.x,Python,Json,Python 3.x,我有一份清单: x = [ {'10:19': 6517}, {'10:20': 6537}, {'10:21': 6557}, {'10:22': 6751}, {'10:23': 6815}, {'10:24': 6984}, {'10:25': 6951}, {'10:26': 6976}, {'10:27': 6786}, {'10:28': 6930}, {'10:29': 1029} ] 我想获

我有一份清单:

x = [
    {'10:19': 6517},
    {'10:20': 6537},
    {'10:21': 6557},
    {'10:22': 6751},
    {'10:23': 6815},
    {'10:24': 6984},
    {'10:25': 6951},
    {'10:26': 6976},
    {'10:27': 6786},
    {'10:28': 6930},
    {'10:29': 1029}
]

我想获取键值,例如10:19:6517`、'10:19':6517等等。如何获取?

您拥有的是一个字典列表,您想将其展平。python的方法是使用理解:

d = {k:v for elt in x for k,v in elt.items()}
print(d)
print(d['10:20'])
如预期所示:

{'10:19': 6517, '10:20': 6537, '10:21': 6557, '10:22': 6751, '10:23': 6815, '10:24': 6984, '10:25': 6951, '10:26': 6976, '10:27': 6786, '10:28': 6930, '10:29': 1029}
6537

这里的理解是对该代码的一种(更有效的)简写:

d = {}
for elt in x:                          # scan the list
    for k, v in elt.items():           # scan the individual dicts
        d[k] = v                       # and feed the result dict
我试试这个,效果很好

for i in x:
    for k,v in i.items():
        print(k,v

我想你有一个列表,而不是字符串。所以你可以这样做:

keys\u list=[key代表key\u值,x代表key代表key-in-key\u值]
#提取列表x中每个dict的值
对于索引,枚举中的项(x,0):
item\u value=item.get(x[索引])
#现在,您有了x[index]中的键和项_值中的值。我只是把它们打印出来,
#你可以用它们做任何你想做的事
打印(f'{x[index]}:{item_value}')

没有列表理解和含义

for i in x:  #for the item in the list x
    for k,v in i.items(): #Since the item in the list is a dict, we get the dict item and unpack it's k(Key) and v(Value).
        print(k,v) # Print Them
输出:-

10:19 6517
10:20 6537
10:21 6557
10:22 6751
10:23 6815
10:24 6984
10:25 6951
10:26 6976
10:27 6786
10:28 6930
10:29 1029

x=[…]不是字符串。这是一份清单。你澄清了吗?对不起是的这是名单
x = [
    {'10:19': 6517},
    {'10:20': 6537},
    {'10:21': 6557},
    {'10:22': 6751},
    {'10:23': 6815},
    {'10:24': 6984},
    {'10:25': 6951},
    {'10:26': 6976},
    {'10:27': 6786},
    {'10:28': 6930},
    {'10:29': 1029}
]

for i in x:                      # iterate on list x
    for key, value in i.values():         # get keys and values 
        print("Key: " + key + ", Value: " + value)