I'd like to return this: {'Feature_Name[value]': {'MY_username':'value','started_my_time':'value'} in python3.5 - python-3.5

Below code i have used but not getting correct output.
def seek_keys(d, key_list):
newdict1 = dict([(vkey, vdata) for vkey, vdata in d.items() if(vdata) ])
dict1={}
for kk,vv in newdict1.items():
if kk in key_list:
dict1[kk]=[]
dict1[kk].append(vv)
print(dict1)
if isinstance(newdict1[kk], dict):
seek_keys(newdict1[kk], key_list)
filtered_list4 = ['Feature_Name', 'MY_username', 'started_my_time']
seek_keys(converted_xml,filtered_list4)
I'd like to return this:
{'Feature_Name[value]': {'MY_username':'value','started_my_time':'value'}
This is the dictionary i am using-
my_dict ={'1': {'Feature_Name': 'Lucky', 'usage_details_for_KD': 'No user details available_bye', 'use_percentage_file': '0%'}, '2': {'Feature_Name': 'Kunal', 'usage_details_for_KD': {'usage_details_for_KD_values': {'1': {'MY_description': 'for ' 'USER', 'started_my_time': '', 'MY_username': '1'}}}}, '3': {'Feature_Name': 'KD_M', 'usage_details_for_KD': {'usage_details_for_KD_values': {'1': {'MY_description': 'KD_DISPLAY ' '(0001)', 'started_my_time': 'Mon 12/23 ' '11:11', 'MY_username': 'KD_SI'}, '2': {'MY_description': 'Hello ' '0001)', 'started_my_time': 'Mon 12/23 ' '12:06', 'MY_username': 'Real_hero'}}}}, '4': {'Feature_Name': 'MY_NAME', 'usage_details_for_KD': {'usage_details_for_KD_values': {'1': {'MY_description': 'KD_DISPLAY ' '0001)',
'started_my_time': 'Mon 12/23 ' '13:57', 'MY_username': 'Same_hero'}}}}, '5': {'Feature_Name': 'Your_NAME', 'usage_details_for_KD': 'No user details available_bye', 'use_percentage_file': '0%'}}

Issue has been resolved, as i manage to solve.
class CoinBuilder_for_user_details:
def __init__(self,dict1,dict2):
self.Feature = dict2['Feature']
self.MY_username = dict1['MY_username']
self.started_my_time = dict1['started_my_time']
def main ():
max_key_all_f=max(converted_xml['Usages'])
for i in range(1,max_key_all_f+1):
if(ign not in converted_xml['Usages'][i]['usage_details_for_KD']):
print("\nFinal output is ")
max_key_user =(max(converted_xml['Usages'][i]['usage_details_for_KD']['usage_details_for_KD_values']))
if(type(max_key_user) == str):
A1=CoinBuilder_for_user_details(converted_xml['Usages'][i]['usage_details_for_KD']['usage_details_for_KD_values'],converted_xml['Usages'][i])
if(A1.statred not in null_v):
print("Feature Name : ",A1.Feature)
print("My User Name : ",A1.MY_username)
print("Date : ",A1.started_my_time)`enter code here`

Related

cant figure out why im getting an key error in python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 14 hours ago.
Improve this question
so, I'm doing this final for school and I can't for the life of me figure out why I'm getting a key Error for 'item' in my code at line 33. any help would be appreciated.
rooms = {
'Cart': {'name': 'Cart', 'East': 'Market District'},
'Market District': {'name': 'Market District', 'South': 'Grayson Armory', 'North': 'Temporal Steel',
'East': 'Mini Mart', 'West': 'Cart', 'item': 'Helm'},
'Temporal Steel': {'name': 'Temporal Steel', 'South': 'Market District',
'East': 'Temporal Storage', 'item': 'Sword'},
'Temporal Storage': {'name': 'Temporal Storage', 'West': 'Temporal Steel', 'item': 'Shield'},
'Grayson Armory': {'name': 'Grayson Armory', 'North': 'Market District', 'East': 'Luds', 'item': 'Chest Plate'},
'Luds': {'name': 'Luds', 'East': 'Grayson Armory', 'item': 'Leggings'},
'Mini Mart': {'name': 'Mini Mart', 'North': 'Gate', 'West': 'Market District', 'item': 'Boots'},
'Gate': {'name': 'Gate', 'South': 'Mini Mart', 'item': 'Gate Guard'}
}
def intructions():
print('Welcome to Carts & Burglars')
print('To escape you must collect all the items and avoid the guards!')
print("The commands to move are 'North', 'South', 'East', and 'West' ")
print("To add an item to inventory: get item ")
intructions()
current_room = rooms['Cart'] # initial room
directions = ['North', 'South', 'East', 'West']
item = ['Helm', 'Chest Plate', 'Leggings', 'Sword', 'Shield', 'Boots']
inventory = {} # players inventory
while True:
print('-' * 35)
print('You are in the {}'.format(current_room['name']))
print('Your inventory: {}\n'.format(inventory))
if current_room['item']:
print('Item in room: {}'.format(''.join(current_room['item'])))
print('')
direction = input('Enter an direction:').title()
if direction in directions:
if direction in current_room:
current_room = rooms[current_room[direction]]
if current_room['name'] == 'Gate':
print("You've reached the gate but the guards coming back!")
if len(inventory.keys()) >= 6:
print('you took out the guard!')
print("You've gotten past the gate and no one knows where you went you have achieved freedom.")
else:
print('The guard noticed you and apprehended you')
print('Game Over.')
break
else:
print('Choose a direction')
elif direction == 'get item':
if current_room['item'] != 'none':
inventory['item' + str(len(inventory.keys()) + 1)] = current_room['item']
print("You looted: ", current_room['item'])
print(inventory)
current_room['item'] = 'none'
else:
print("theres nothing here to loot")
elif direction == 'quit':
print('Maybe next time!')
break
else:
print('Invalid input.')
I've tried manipulating the inventory and item variables at the top of the code as well deleting like 33-35 and it works just fine but I need the items to be there and to state what items are in the room.
type here

Parallelise / Threading a big for loop | Python

I have a working Jupyter Notebook that models fake data in the form of a dictionary. Using Faker library and other basic Python.
Reading other posts, parallelism seems to be used on methods. However, I want to apply this technique on the big for loop; as I have many more "key-value lists" applied in the process.
Note: I've appended comments of list slicing included in the process, in case that's needed.
Is it possible to run multiple iterations of a for loop at once? (or as many as possible)
from faker import Faker
faker = Faker()
Faker.seed(1)
import pandas as pd
import random
random.seed(1)
# Key Value lists
biographic_keys = [['Name', 'faker.unique.name()'], ['Aliases', 'faker.unique.user_name()'], ['Date of birth', 'faker.unique.date_of_birth().isoformat()'], ['Phone numbers', 'faker.unique.phone_number()'], ['Addresses', 'faker.unique.address()'], ['Nationality', 'faker.unique.country()'], ['Social Security Number', 'faker.unique.ssn()'], ['Alien File Number', 'random.randrange(1000000, 999999999, random.randint(7, 9))']]
biometric_keys = [['Height', "'{}ft {}inch'.format(random.randint(4, 7), random.randint(0, 11)) if random.randint(0, 1) == 1 else '{}cm'.format(random.randint(100, 200))"], ['Weight', "'{}kg'.format(random.randint(60, 130)) if random.randint(0, 1) == 1 else '{}st {}lb'.format(random.randint(7, 50), random.randint(0, 13))"], ['Eye color', "random.choice(['Amber', 'Blue', 'Brown', 'Gray', 'Green', 'Hazel'])"], ['Hair color', "random.choice(['Brown', 'Blond', 'Black', 'Auburn', 'Red', 'Gray', 'White', 'Bald'])"]]
entries = 4
alien_key_val = []
alien_key_val.append(["Biographic data", biographic_keys])
alien_key_val.append(["Biometric data", biometric_keys])
#print(alien_key_val[0]) # name, subset
#print(alien_key_val[0][0]) # name
#print(alien_key_val[0][1]) # subset
#print(alien_key_val[0][1][0][0]) # key
#print(alien_key_val[0][1][0][1]) # invoke val
# Programmatic key-values
alien_dict = {}
for entry in range(1, entries+1):
entry_dict = {}
for i, subset in enumerate(alien_key_val):
subset_dict = {}
subset_name = alien_key_val[i][0]
for data in subset[1]:
key, invoc = data[0], data[1]
#if ('faker.unique.' in invoc) or ('random.' in invoc) or ('tf.' in invoc) or ("''.join" in invoc) or ("'{}" in invoc): val = eval(invoc)
if invoc[-1] != ':': val = eval(invoc)
else: val = ""
if 'Identification numbers' in key: val = {i[0]: i[1] for i in val}
subset_dict.update({key: val})
entry_dict.update({subset_name: subset_dict})
alien_dict.update({'id_' + str(entry): entry_dict})
print("\nALIEN_DICT:\n", alien_dict)
>>> ALIEN_DICT:
{'id_1': {'Biographic data': {'Name': 'Ryan Gallagher', 'Aliases': 'david77', 'Date of birth': '1994-03-12', 'Phone numbers': '(317)066-9074x3915', 'Addresses': '806 Tanya Stream\nNew Jeffreymouth, OH 31051', 'Nationality': 'Guatemala', 'Social Security Number': '237-87-3585', 'Alien File Number': 119580763}, 'Biometric data': {'Height': '4ft 7inch', 'Weight': '120kg', 'Eye color': 'Hazel', 'Hair color': 'White'}}, 'id_2': {'Biographic data': {'Name': 'Tiffany House', 'Aliases': 'jmonroe', 'Date of birth': '1992-12-05', 'Phone numbers': '241-586-8344', 'Addresses': '690 Sanchez Union Suite 625\nChristopherhaven, WI 21957', 'Nationality': 'Maldives', 'Social Security Number': '861-51-6071', 'Alien File Number': 177366680}, 'Biometric data': {'Height': '4ft 6inch', 'Weight': '60kg', 'Eye color': 'Hazel', 'Hair color': 'Bald'}}, 'id_3': {'Biographic data': {'Name': 'Allen Williams DDS', 'Aliases': 'kholland', 'Date of birth': '1973-11-13', 'Phone numbers': '038.836.8595', 'Addresses': '890 Bowers View Apt. 883\nHerringfort, MN 75211', 'Nationality': 'Mexico', 'Social Security Number': '205-65-6774', 'Alien File Number': 775747704}, 'Biometric data': {'Height': '175cm', 'Weight': '27st 0lb', 'Eye color': 'Amber', 'Hair color': 'Brown'}}, 'id_4': {'Biographic data': {'Name': 'Mr. Gregory Ryan', 'Aliases': 'stephen03', 'Date of birth': '1991-12-27', 'Phone numbers': '(892)184-0110', 'Addresses': '41925 Jones Estate Suite 824\nShawnmouth, NJ 15468', 'Nationality': 'Anguilla', 'Social Security Number': '320-50-5626', 'Alien File Number': 655004368}, 'Biometric data': {'Height': '148cm', 'Weight': '34st 11lb', 'Eye color': 'Amber', 'Hair color': 'Auburn'}}}
Solution appended below. Please add a solution if you believe yours is a better alternative. I'd love to learn other approaches for the future.
Inspired by Simple multithread for loop in Python
top solution.
Using multiprocessing.dummy as mp and converting my for loop grand procedure into a function.
All "entry" dictionaries are collected into list dicts and are added to dictionary big_boi_dict as originally intended.
...
def alien_dict_func(entry):
# Programmatic key-values
alien_dict = {}
entry_dict = {}
for i, subset in enumerate(alien_key_val):
subset_dict = {}
subset_name = alien_key_val[i][0]
for data in subset[1]:
key, invoc = data[0], data[1]
#if ('faker.unique.' in invoc) or ('random.' in invoc) or ('tf.' in invoc) or ("''.join" in invoc) or ("'{}" in invoc): val = eval(invoc)
if invoc[-1] != ':': val = eval(invoc)
else: val = ""
if 'Identification numbers' in key: val = {i[0]: i[1] for i in val}
subset_dict.update({key: val})
entry_dict.update({subset_name: subset_dict})
alien_dict.update({'id_' + str(entry): entry_dict})
#print("\nALIEN_DICT:\n", alien_dict)
return alien_dict
import multiprocessing.dummy as mp
if __name__=="__main__":
p=mp.Pool(4)
dicts = p.map(alien_dict_func, range(1, entries+1)) # range(0,1000) if you want to replicate your example
#print("DICTS: ", dicts)
big_boi_dict = {}
for d in dicts: big_boi_dict.update(d)
print("big_boi_dict: ", big_boi_dict)
p.close()
p.join()
>>> big_boi_dict: {'id_1': {'Biographic data': {'Name': 'Jacob Gaines', 'Aliases': 'laurenswanson', 'Date of birth': '2016-04-20', 'Phone numbers': '630-868-7169x899', 'Addresses': '0340 Lydia Passage Suite 898\nAliciaside, NC 54017', 'Nationality': 'Netherlands Antilles', 'Social Security Number': '646-75-5043', 'Alien File Number': 216185864}, 'Biometric data': {'Height': '4ft 3inch', 'Weight': '84kg', 'Eye color': 'Gray', 'Hair color': 'Blond'}}, 'id_2': {'Biographic data': {'Name': 'Carlos Wallace', 'Aliases': 'andreabray', 'Date of birth': '1927-09-11', 'Phone numbers': '069-056-6401x106', 'Addresses': '7567 Timothy Drive Suite 202\nMichealberg, WY 38137', 'Nationality': 'Zambia', 'Social Security Number': '423-34-8418', 'Alien File Number': 472177351}, 'Biometric data': {'Height': '7ft 0inch', 'Weight': '111kg', 'Eye color': 'Amber', 'Hair color': 'Brown'}}, 'id_3': {'Biographic data': {'Name': 'Jason Hill', 'Aliases': 'kimberly73', 'Date of birth': '2002-11-20', 'Phone numbers': '661.123.2301x4271', 'Addresses': '16908 Amanda Key\nLake Taraville, OH 89507', 'Nationality': 'Italy', 'Social Security Number': '855-86-1944', 'Alien File Number': 20427192}, 'Biometric data': {'Height': '125cm', 'Weight': '77kg', 'Eye color': 'Brown', 'Hair color': 'White'}}, 'id_4': {'Biographic data': {'Name': 'Melinda White PhD', 'Aliases': 'hartmanerica', 'Date of birth': '1917-05-19', 'Phone numbers': '(174)876-1971x2693', 'Addresses': '8478 Kristina Road Suite 710\nSaraview, ND 82480', 'Nationality': 'French Southern Territories', 'Social Security Number': '779-13-3745', 'Alien File Number': 501832948}, 'Biometric data': {'Height': '148cm', 'Weight': '128kg', 'Eye color': 'Gray', 'Hair color': 'Auburn'}}}
For the question of accessing every element in the loop simultaneously. I tried something like that
import time
import threading
class handle_data(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self): # handle_data
print ("Starting " + self.name)
print(self.name, 5, self.counter)
print("Exiting " + self.name)
def stop(self):
self.running = False
if __name__ == "__main__":
for data in range(10):
handle_data(data,"Thread-"+str(data),data).start()

Need help defining a function for text based game

I am trying to code out a function for this project. I am new to python and am taking a class online for it. I am trying to define a function that will read what room my player is in and to give the riddle associated with it. so far this is what I have, there is another dictionary that current_room works with. I just keep getting key errors when trying to test run. If there is a better way to do this as well, please let me know.
EDIT: updating with whole code
# The dictionary links a room to other rooms.
rooms = {'Warehouse Storage': {'name': 'Warehouse Storage', 'south': 'Stamping Area',
'text': 'You are in the Warehouse Storage.'},
'Machine Shop': {'name': 'Machine Shop', 'east': 'Scrap Pile', 'south': 'Staging Area',
'text': 'You are in the Machine Shop.'},
'Front Offices': {'name': 'Front Offices', 'west': 'Lunchroom',
'text': 'You are in Front Offices.'},
'Stamping Area': {'name': 'Stamping Area', 'west': 'Staging Area', 'north': 'Warehouse Storage',
'text': 'You are in the Stamping Area'},
'Loading Docks': {'name': 'Loading Docks', 'east': 'Staging Area',
'text': 'You are in the Loading Docks'},
'Staging Area': {'name': 'Staging Area', 'east': 'Stamping Area', 'west': 'Loading Docks',
'south': 'Lunchroom', 'north': 'Machine Shop',
'text': 'You are in the Staging Area'},
'Lunchroom': {'name': 'Lunchroom', 'north': 'Staging Area', 'east': 'Front Offices',
'text': 'You are in the Lunchroom'},
'Scrap Pile': {'name': 'Scrap Pile', 'west': 'Machine Shop',
'text': 'You are in the Scrap Pile'}
}
riddles = {'Warehouse Storage': {'name': 'Warehouse Storage', 'question': '', 'answer': ''},
'Machine Shop': {'name': 'Machine Shop', 'question': '', 'answer': ''},
'Stamping Area': {'name': 'Stamping Area', 'question': '', 'answer': ''},
'Staging Area': {'name': 'Staging Area', 'question': '', 'answer': ''},
'Lunchroom': {'name': 'Lunchroom', 'question': 'riddle', 'answer': 'yes'},
'Scrap Pile': {'name': 'Scrap Pile', 'question': '', 'answer': ''}
}
# define function that reads room and prompts user with riddle
def room_puzzle(current_room):
global user_inventory
if current_room in riddles.keys():
riddle = input(f'{riddles[current_room]["question"]} \n').strip()
if riddle == riddles[current_room]['answer']:
user_inventory += 1
print('You gained a key')
else:
print('that is incorrect')
return user_inventory
else:
print("no such room")
# determine command regardless of capitalization
def dir_input(text):
if text.upper().startswith('W'):
return 'west'
elif text.upper().startswith('N'):
return 'north'
elif text.upper().startswith('S'):
return 'south'
elif text.upper().startswith('E'):
return 'east'
elif text.upper().startswith('Q'):
return 'quit'
directions = ['north', 'south', 'east', 'west']
current_room = rooms['Front Offices']
print('Would you like to play a game?')
start = input()
game_start = False
user_inventory = 0 # start at zero
if start == 'yes' or start == 'Yes':
game_start = True
# game loop
while game_start == True:
# win condition
if current_room['name'] == 'Loading Docks':
if user_inventory == 6:
print(current_room['text'])
else:
print('6 keys are required to enter')
# display current location
print()
print(current_room['text'])
# get user input
command = input('\nWhat do you do? ').strip()
# show inventory
if command == 'show inventory':
print('You have {} keys'.format(user_inventory))
# movement
elif command in directions:
command = dir_input(command)
if command in current_room:
current_room = rooms[current_room[command]]
#room_puzzle()
else:
# not a valid input
print("You can't go that way.")
# quit game
elif command == 'quit':
break
# does not compute
else:
print("I don't understand that command.")
See basically what I observe from the above code is that you want to check whether the current_room is equal to Lunchroom or not or for any other rooms you have in your riddles dictionary.
So for that, you have to check for the presence of a key in the dictionary not for the values. Also, the below part is incorrect in your code
if current_room in riddles['name']:
instead, it should be
if current_room in riddles.keys():
and the part of code if riddle == riddles['answer']: is incorrect as the you are not passing the right reference to the dictionary key
it should be if riddle == riddles[current_room]['answer']:
so here is the correct code with the working demo for you to understand.
riddles = {'Lunchroom': {'name': 'Lunchroom', 'question': 'riddle?', 'answer': 'yes'}}
def room_puzzle(current_room):
global user_inventory
if current_room in riddles.keys():
riddle = input('{}'.format(riddles[current_room]['question'])).strip()
if riddle == riddles[current_room]['answer']: # here you have to define the refrence to the dictionary value, using the parent key first
# user_inventory += 1
print('You gained a key')
else:
print('that is incorrect')
# return user_inventory
else:
print("no such room")
current_room = 'Lunchroom' #let's assume for now
room_puzzle(current_room)
current_room = 'Someroom' #let's now change the current_room and check that
room_puzzle(current_room)

Print "no value" on indices that are out of range

Here is my code:
x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']
List = []
i = 0
while i < len(x):
a = 1
name_list = 'list' + str(a)
name_list = {
'wife_code': x[i+1],
'wife_list': x[i],
'husband_code': x[i+3],
'husband_list': x[i+2],
}
List.append(name_list)
a += 1
i += 4
print(List)
Upon running the code, it is throwing "IndexError: list index out of range". I know that the error is happening in the 3rd loop because it doesn't have a 'husband_code' and 'husband_list'. Is there a way to print "no value" on that indices that are out of range?
Expected output:
[{'wife_code': 'ann', 'wife_list': 'D4B3', 'husband_code': 'richard', 'husband_list': 'A4N5'},
{'wife_code': 'lily', 'wife_list': 'M3L1', 'husband_code': 'david', 'husband_list': 'P4N5'},
{'wife_code': 'bea', 'wife_list': 'S3B2', 'husband_code': 'no value', 'husband_list': 'no value'}]
Use itertools.zip_longest with dict
Ex:
from itertools import zip_longest
x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']
result = []
keys = ['wife_list', 'wife_code', 'husband_list', 'husband_code']
for i in range(0, len(x), 4):
result.append(dict(zip_longest(keys, x[i:i+4], fillvalue='no value')))
print(result)
with a list comprehension
Ex:
result = [dict(zip_longest(keys, x[i:i+4], fillvalue='no value')) for i in range(0, len(x), 4)]
Output:
[{'husband_code': 'A4N5',
'husband_list': 'richard',
'wife_code': 'D4B3',
'wife_list': 'ann'},
{'husband_code': 'P4N5',
'husband_list': 'david',
'wife_code': 'M3L1',
'wife_list': 'lily'},
{'husband_code': 'no value',
'husband_list': 'no value',
'wife_code': 'S3B2',
'wife_list': 'bea'}]

List containing lists (matrix) as input() with python 3

I'm trying to convert a given input to a list containing lists as shown in the command-line code below:
matrix = input('asking')
asking[[2, 0, 4],[1, 2, 4],[4, 4, 2]]
matrix
'[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
desired output:
[[2,0,4],[1,2,4],[4,4,2]]
Attempts
list(matrix)
['[', '[', '2', ',', ' ', '0', ',', ' ', '4', ']', ',', ' ', '[', '1', ',', ' ', '2', ',', ' ', '4', ']', ',', ' ', '[', '4', ',', ' ', '4', ',', ' ', '2', ']', ']']
x = [int(a) for a in matrix]
builtins.TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
matrix.split(',')
['[[2', '0', '4]', '[1', '2', '4]', '[4', '4', '2]]']
Code:
fin_result = 0
def perform_check():
print("Enter form \n [[a,b,c] \n [d,e,f] \n [g,h,i]]")
#ask_for_input = [[4,-1,1],[4,5,3],[-2,0,0]]
ask_for_input = [[2,0,4],[1,2,4],[4,4,2]]
print(type(ask_for_input))
#call function to cont
calculate_determinate_matrix(ask_for_input)
def calculate_determinate_matrix(matrix3x3):
matrix_list2x2 = []
matrix_list2x2.append([[matrix3x3[1][1], matrix3x3[1][2]], [matrix3x3[2][1], matrix3x3[2][2]]])
matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][2]],[matrix3x3[2][0], matrix3x3[2][2]]])
matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][1]],[matrix3x3[2][0], matrix3x3[2][1]]])
count = 0
for count, matrix_2x2 in enumerate(matrix_list2x2):
if count % 2 == 1:
calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count] * -1)
else:
calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count])
def calculate_2x2_matrix(matrix, mult):
global fin_result
result = matrix[0][0] * matrix[1][1]
result_2 = matrix[0][1] * matrix[1][0]
fin_result += mult * (result - result_2)
def main():
perform_check()
print(fin_result)
if __name__ == "__main__":
main()
Clearly this code needs work, but I can't figure this in terms of list comprehension.
Use json loads() method:
matrix = '[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
matrix = json.loads(matrix)
type(matrix)
<type 'list'>
And in case you want to check for errors in input you can wrap it in try-except:
try:
matrix = json.loads(matrix)
except ValueError:
#code goes here
An alternative to json.loads is ast.literal_eval. It has the advantage that it recognizes Python syntax even if it was invalid JSON, like single-quoted strings. In your exact case, it doesn't make a difference:
import ast
matrix = '[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
matrix = ast.literal_eval(matrix)

Resources