0

A have an array like this

{  
    "records":[  
        {  
            "domain":"example.com",
            "fqdn":"111",
        },
        {  
            "domain":"example.com",
            "fqdn":"2222",
        },
        {  
            "domain":"example.com",
            "fqdn":"333",
        },
    ],
}

How can I get index of element with fqdn == "333"?

2
  • I know, that I can use for, but I hope, that there is another way Commented Feb 12, 2015 at 9:33
  • I'm wondering why you need this index in the first place. Can you tell us more - most probably, there's a better way. Commented Feb 12, 2015 at 9:44

3 Answers 3

3

You can use a list comprehension with enumerate:

[x for x, y in enumerate(data['records']) if y['fqdn'] == '333'][0]

You'd have to catch IndexError for the case where it didn't exist, though.

As suggested in the comments, you could avoid the issues of redundant lookups for duplicate target values, and catching IndexError, by using a generator and next:

next((x for x, y in enumerate(data['records']) if y['fqdn'] == '333'), None)
Sign up to request clarification or add additional context in comments.

2 Comments

If there's more than one target value, your code will make redundant lookups.
You can also use a generator expr instead of a comp, next((...), None) thus avoiding an exception and the problem in the ^^^ comment.
1

Seems like you want something like this,

>>> d = {  
    "records":[  
        {  
            "domain":"example.com",
            "fqdn":"111",
        },
        {  
            "domain":"example.com",
            "fqdn":"2222",
        },
        {  
            "domain":"example.com",
            "fqdn":"333",
        },
    ],
}
>>> for i in d.values():
        for s,m in enumerate(i):
            if m['fqdn'] == "333":
                print(s)


2

Comments

0
li = list(di['records'])
for x in li:
    for k, v in x.items():
        if v == '333':
            print k, v

1 Comment

Usually it is helpful to include some text which explains how the code answers the question or solves the problem in addition to bare code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.