user14499766
user14499766

Reputation:

python get key values from string

I have a list:

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}
]

I want to get the key value for example 10:19 : 6517` , '10:19': 6517 and etc. how to get ?

Upvotes: 0

Views: 67

Answers (4)

Gunobaba
Gunobaba

Reputation: 176

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)

Upvotes: 1

Andrei Gurko
Andrei Gurko

Reputation: 369

I think you have a list, not a string. So you can do this:

keys_list = [key for key_value in x for key in key_value]
# extracting value of every dict in list x
for index, item in enumerate(x, 0):
    item_value = item.get(x[index])
    # now you have key in x[index] and value in item_value. I just print them, 
    #  you can do anything what you want with them
    print(f'{x[index]}:{item_value}')

Upvotes: 0

Abhishek Rai
Abhishek Rai

Reputation: 2227

Without List comprehension and meaning.

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

Output:-

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

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148900

What you have is a list of dictionaries, and you want to flatten it. The Pythonic way is to use a comprehension:

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

gives as expected:

{'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

Here the comprehension is a (more efficient) shorthand for this code:

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

Upvotes: 1

Related Questions