Python Forum

Full Version: AttributeError: 'list' object has no attribute 'values'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a query. My query returns the result that i want as a dictionary.

Like:

[{'community_string': 'public'}, {'community_string': 'private'}]
I want to use only public and private as a string. For doing it, i wrote my code like that:

query= "SELECT community_string FROM nat_snmp_string WHERE status ='enable'" cursor = connection.cursor(dictionary=True) cursor.execute(query) com_str = cursor.fetchall() com_str_string = com_str.values() cmnyt_str = json.dumps(list(com_str)) print(cmnyt_str) cmd_line = cmnyt_str.replace(':','') cmd_line = cmd_line.replace('"','') cmd_line = cmd_line.replace(']','') cmd_line = cmd_line.replace('[','') 
but it gives me AttributeError: 'list' object has no attribute 'values' error.
How can i solve this issue?
Thank you for your helps.
The error is from trying to access a list like a dict.

you can use the list index to access the data or loop the list to get the data.

com_str = [{'community_string': 'public'}, {'community_string': 'private'}] print('list index') print(f"{com_str[0]['community_string']} | {com_str[1]['community_string']}") print() print('looping') for data in com_str: print(data['community_string']) print() print('One liner') print('\n'.join([data['community_string'] for data in com_str]))
Output:
list index public | private looping public private One liner public private
Thank you for your answer. But in my db, there may be more than 2 attribute. In this case i cant write all like that:

com_str = [{'community_string': 'public'}, {'community_string': 'private'}] print(f"{com_str[0]['community_string']} |
{com_str[1]['community_string']}")
(Jan-19-2022, 08:25 AM)menator01 Wrote: [ -> ]The error is from trying to access a list like a dict.

you can use the list index to access the data or loop the list to get the data.

com_str = [{'community_string': 'public'}, {'community_string': 'private'}] print('list index') print(f"{com_str[0]['community_string']} | {com_str[1]['community_string']}") print() print('looping') for data in com_str: print(data['community_string']) print() print('One liner') print('\n'.join([data['community_string'] for data in com_str]))
Output:
list index public | private looping public private One liner public private

Thank you very much!
Then you will need to use some type of loop