0

How do I parse an item from the list in python?

I need to get a HOSTNAME from: {'Key': 'Name', 'Value': 'HOSTNAME'}

tag = [{'Key': 'Backup Initiator Rule', 'Value': 'Daily-6d-retention'}, 
        {'Key': 'delete_On', 'Value': '2019-08-31'},
        {'Key': 'Backup_Type', 'Value': 'Demo'},
        {'Key': 'Name', 'Value': 'HOSTNAME'},
        {'Key': 'Disaster_Recovery', 'Value': 'Full'}]
6
  • get tag["Tags"] then scan the list for a dictionary where Key == Name. Use ast.literal_eval on it first since it seems to be a string Commented Aug 29, 2019 at 13:23
  • 1
    this appears to be a python dictionary written to string. why? can you change that? Commented Aug 29, 2019 at 13:25
  • but this string contains a "datetime.datetime" call... 'StartTime': datetime.datetime(2019, 8, 28, 13, 56, 8, 269000, tzinfo=tzutc()), Commented Aug 29, 2019 at 13:28
  • i expect that that's not a call that's a datetime object's string representation Commented Aug 29, 2019 at 13:30
  • type of variable tag is the class 'list' Commented Aug 29, 2019 at 14:04

3 Answers 3

1

Try List Comp:

tag = "[{'Key': 'Backup Initiator Rule', 'Value': 'Daily-6d-retention'}, {'Key': 'delete_On', 'Value': '2019-08-31'},{'Key': 'Backup_Type', 'Value': 'Demo'},{'Key': 'Name', 'Value': 'HOSTNAME'},{'Key': 'Disaster_Recovery', 'Value': 'Full'}]"

print([dic['Value'] for dic in eval(tag) if dic['Key']=='Name'])

Results: ['HOSTNAME']

Sign up to request clarification or add additional context in comments.

3 Comments

how to be in case if the type of variable 'tag' is class 'list'
tag = [{'Key': 'Backup Initiator Rule', 'Value': 'Daily-6d-retention'}, {'Key': 'delete_On', 'Value': '2019-08-31'},{'Key': 'Backup_Type', 'Value': 'Demo'},{'Key': 'Name', 'Value': 'HOSTNAME'},{'Key': 'Disaster_Recovery', 'Value': 'Full'}]
Just change "eval(tag)" to tag.
1

Regex

Since this is not parseable json i would go for the regex way:

import re
re.findall("{'Key': 'Name', 'Value': '(.*?)'}", tag)

This returns a list of all objects found:

['HOSTNAME']

Edit OP changed the tag string, this might not be the best option now.

Comments

0
for dict in tag:
    if dict['Key'] == 'Name':
        hostname = dict['Value']
        break

1 Comment

I meant list <class 'list'>

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.