KoKo
KoKo

Reputation: 379

Given a known value in a key-value pair, extract the value of the next key-value pair in a dictionary

I have a list of dictionaries with each dictionary containing two key-value pairs as shown (this is only a small subset of the list)

G=[{j:0,vi:0},{j:1,vi:1},{j:2,vi:2},{j:3,vi:3}]

I'm using an If statement to find out if the current vi already exists in the list of dictionary

if any('vi' in d.keys() for d in G]: 

Then I want to get the j value of that particular dictionary that contains the current vi. Thus if vi is 1, I want to get the 1 from j:1. This j value will be used as a column pointer for the matrix I'm building. I'm not sure how to go about this. Any pointers would help.

Note that the G list of dictionaries keeps growing with each iteration

i have tried various key-value extract answers here but they are all for extracting a specific key or value and not for another key or value in the same dictionary.

Upvotes: 0

Views: 43

Answers (1)

J_H
J_H

Reputation: 20460

You wrote:

if vi in G.viewvalues():

You wanted:

if any('vi' in d
       for d in G):

You tagged the question as python3, but used a python2 language feature.

Possibly you want to write a generator function with behavior like this:

for d in G:
    if d.get('vi') == current_vi_value:
        yield d['j']

Upvotes: 1

Related Questions