I have the following list and am wanting to convert it into a dictionary where the 4 digit value at the start of each item becomes the id.
['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
I have tried many different methods but it doesn't seem to work.
You can use str.split, map and dictionary comprehension
# data holds the list you have provided
{splitted[0]:splitted[1:] for splitted in map(lambda item:item.split(','), data)}
OUTPUT:
Out[35]:
{'3574': ['A+', '2021-03-24'],
'3575': ['O+', '2021-04-03'],
'3576': ['AB-', '2021-04-09'],
'3580': ['AB+', '2021-04-27'],
'3589': ['A+', '2021-05-08'],
'3590': ['B-', '2021-05-11']}
You can use dictionary comprehension with str.split:
lst = [
"3574,A+,2021-03-24",
"3575,O+,2021-04-03",
"3576,AB-,2021-04-09",
"3580,AB+,2021-04-27",
"3589,A+,2021-05-08",
"3590,B-,2021-05-11",
]
out = {int(v.split(",")[0]): v.split(",")[1:] for v in lst}
print(out)
Prints:
{
3574: ["A+", "2021-03-24"],
3575: ["O+", "2021-04-03"],
3576: ["AB-", "2021-04-09"],
3580: ["AB+", "2021-04-27"],
3589: ["A+", "2021-05-08"],
3590: ["B-", "2021-05-11"],
}
Here is the code to do what I believe you asked for. I have also added comments in the code for a bit more clarification.
my_list = ['3574,A+,2021-03-24',
'3575,O+,2021-04-03',
'3576,AB-,2021-04-09',
'3580,AB+,2021-04-27',
'3589,A+,2021-05-08',
'3590,B-,2021-05-11']#your list
my_dict = {}#The dictionary you want to put the list into
print("Your list:", my_list, "\n")
for item in my_list:#cycles through every item in your list
ID, value = item.split(",", 1)#Splits the item in your list only once (when it sees the first comma)
print(ID + ": " + value)
my_dict[ID] = value#Add the ID and value to your dictionary
print("\n" + "Your desired dictionary:", my_dict)
Which outputs this:
Your list: ['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
3574: A+,2021-03-24
3575: O+,2021-04-03
3576: AB-,2021-04-09
3580: AB+,2021-04-27
3589: A+,2021-05-08
3590: B-,2021-05-11
Your desired dictionary: {'3574': 'A+,2021-03-24', '3575': 'O+,2021-04-03', '3576': 'AB-,2021-04-09', '3580': 'AB+,2021-04-27', '3589': 'A+,2021-05-08', '3590': 'B-,2021-05-11'}
Enjoy!
TRY:
result = dict(i.split(',', 1) for i in lst)
OUTPUT:
{'3574': 'A+,2021-03-24',
'3575': 'O+,2021-04-03',
'3576': 'AB-,2021-04-09',
'3580': 'AB+,2021-04-27',
'3589': 'A+,2021-05-08',
'3590': 'B-,2021-05-11'}
Related
I have a list of list elements that I'm modifying. And after that modification I want to put them into a list that have the same structure as the original one:
list_data_type = [
[['void1']], [['uint8']], [['uint8'], ['uint32']], [['void2']], [['void3']], [['void4']], [['void5']]
]
Firstly I check for elements that have more than one element. So in this case that would be element with index number = 2. Then I change it into a string, strip it from brackets [] and " " marks and convert it to a list. Then I take other elements and do the same thing. After conversion I want to create a new list with those elements, but without unnecessary symbols. So my desired output would look like this:
list_data_converted = [
['void1'], ['uint8'], ['uint8', 'uint32'], ['void2'], ['void3'], ['void4'], ['void5']
]
Conversion works and I can print out elements, but I have a problem with appending them to a list. My code saves only last value from original list:
def Convert(string):
li = list(string.split(" "))
return li
for element in list_data_type:
if type(element) == list:
print("element is a:", element, type(element))
if len(element) > 1:
id_of_el = list_data_type.index(element)
el_str = str(element).replace('[', '').replace("'", '').replace("'", '').replace(']', '').replace(',', '')
el_con = Convert(el_str)
elif len(element <= 1):
elements_w_1_el = element
list_el = []
for i in range(len(elements_w_1_el)):
el_str_2 = str(element).replace('[', '').replace("'", '').replace("'", '').replace(']', '').replace(',', '')
list_el.append(elements_w_1_el[i])
And my out instead looking like "list_data_converted", has only one element - ['void5']. How do I fix that?
Converting a list to a string to flatten it is a very... cumbersome approach.
Try simple list-comprehension:
list_data_type = [[v[0] for v in l] for l in list_data_type]
Type casting the list into a string and then replacing the characters and then again converting the string into list might be bad way to achieve what you're doing.
Try this :
def flatten(lst):
if lst == []:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
list_data_converted = [flatten(element) for element in list_data_type]
This actually flattens any list item inside list_data_type and keep them in a single list. This should work with any depth of list inside list.
Output print(list_data_converted) would give the following :
[
['void1'], ['uint8'], ['uint8', 'uint32'], ['void2'], ['void3'], ['void4'], ['void5']
]
I need to get:
'W1NaCl U1NaCl V1NaCl'
from:
[['W1NaCl'], ['U1NaCl'], ['V1NaCl']]
How to get required output in pythonic way
items = [['W1NaCl'], ['U1NaCl'], ['V1NaCl']]
res = " ".join([item[0] for item in items])
Which yields: W1NaCl U1NaCl V1NaCl
You can do:
[[i] for i in 'W1NaCl U1NaCl V1NaCl'.split()]
Split will chop it into words, and the list comprehension will make the inner-arrays
I am defining a list of dictionaries and I need to print only the one dictionary based on my input in check_if_in_list
first_list = {'a':'1','b':'2'}
second_list = {'a':'10','b':'20'}
all_lists =[first_list, second_list]
for element in all_lists:
check_if_in_list = input('give a valid number')
if check_if_in_list = (item['a'] for item in all_lists):
I need something like that
print(element where item['a]=check_if_in_list)
for example if I enter '1' in input in check_if_in_list, the print should be :
{'a':'1','b':'2'}
This will give you the output you require. If I have interpreted your requirement correctly, it's actually much simpler than the (I assume) semi-pseudocode that you posted.
first_dict = {'a':'1','b':'2'}
second_dict = {'a':'10','b':'20'}
all_dicts =[first_dict, second_dict]
check_if_in_list = input('give a valid number')
for element in all_lists:
if check_if_in_list == element['a']:
print(element)
If you need it as a comprehension, this would work:
print(*[element for element in all_lists if element['a'] == check_if_in_list])
This utilises star-unpacking to return the values of the list for printing, which should either be a dictionary or nothing in your case. (Thanks to #HampusLarsson for the reminder).
If your original code, you're looping over all_lists twice, which is unnecessary.
I have been trying this for weeks! I tried this for weeks and all i get is nothing!
I searched internet and also the great STACK OVERFLOW but I couldn't find the one i need for!
Well normally if we try to change lists into dictionary we would get space between key and value!
for example:
Output:
The result dict is : {'Stack': '10'}
Well, I want the output as follows:
The result dict is : {'Stack':'10'}
Well the zip function would give a space between them and cause me an error!
And this is the result I have to get:
Enter list elements separated by ,(Comma) for list1: Stack,Over,Flow
Enter list elements separated by ,(Comma) for list2: 111,222,333
{'Stack':'111','Over':'222','Flow':'333'}
and for the code I tried is:
List_1 = input('Enter list elements separated by ,(Comma): ').split(',')
List_2 = input('Enter list elements separated by ,(Comma): ').split(',')
if len(List_1) == len(List_2) and len(List_1) != 0 and len(List_2) != 0 :
dict = dict(zip(List_1, List_2))
print(dict)
else:
print('The two lists are of different lengths. Try again.')
Since you want to be quite specific about the output I would do something like this:
def condensed_dict(data):
output = []
for item in data.items():
output.append('%r:%r' % item)
return '{%s}' % ''.join(output)
List_1 = input('Enter list elements separated by ,(Comma): ').split(',')
List_2 = input('Enter list elements separated by ,(Comma): ').split(',')
if List_1 and len(List_1) == len(List_2):
dict = dict(zip(List_1, List_2))
print(condensed_dict(dict))
else:
print('The two lists are of different lengths. Try again.')
PS: I simplified your if statement a bit.
Build your own string from the zipped lists directly, rather than using a dict.
>>> "{%s}" % ",".join(f"'{k}':'{v}'" for k, v in zip(List_1, List_2))
"{'Stack':'111','Over':'222','Flow':'333'}"
If you already have the dict, then build the string from the output of its items method.
>>> d = dict(zip(List_1, List2))
>>> "{%s}" % ",".join(f"'{k}':'{v}'" for k, v in d.items())
"{'Stack':'111','Over':'222','Flow':'333'}"
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
print ("Original key list is : " + str(test_keys))
print ("Original value list is : " + str(test_values))
# using zip()
# to convert lists to dictionary
res = dict(zip(test_keys, test_values))
print ("Resultant dictionary is : " + str(res))
I have a single list that could be any amount of elements.
['jeff','ham','boat','','my','name','hello']
How do I split this one list into two lists or any amount of lists depending on blank string elements?
All these lists can then be put into one list of lists.
If you are certain that there is only one blank string in the list, you can use str.index to find the index of the blank string, and then slice the list accordingly:
index = lst.index('')
[lst[:index], lst[index + 1:]]
If there could be more than one blank string in the list, you can use itertools.groupby like this:
lst = ['jeff','ham','boat','','my','name','hello','','hello','world']
from itertools import groupby
print([list(g) for k, g in groupby(lst, key=bool) if k])
This outputs:
[['jeff', 'ham', 'boat'], ['my', 'name', 'hello'], ['hello', 'world']]
Using itertools.groupby, you can do:
from itertools import groupby
lst = ['jeff','ham','boat','','my','name','hello']
[list(g) for k, g in groupby(lst, key=bool) if k]
# [['jeff', 'ham', 'boat'], ['my', 'name', 'hello']]
Using bool as grouping key function makes use of the fact that the empty string is the only non-truthy string.
This is one approach using a simple iteration.
Ex:
myList = ['jeff','ham','boat','','my','name','hello']
result = [[]]
for i in myList:
if not i:
result.append([])
else:
result[-1].append(i)
print(result)
Output:
[['jeff', 'ham', 'boat'], ['my', 'name', 'hello']]
Let list_string be your list. This should do the trick :
list_of_list=[[]]
for i in list_string:
if len(i)>0:
list_of_list[-1].append(i)
else:
list_of_list.append([])
Basically, you create a list of list, and you go through your original list of string, each time you encounter a word, you put it in the last list of your list of list, and each time you encounter '' , you create a new list in your list of list. The output for your example would be :
[['jeff','ham','boat'],['my','name','hello']]
i'm not sure that this is what you're trying to do, but try :
my_list = ['jeff','ham','boat','','my','name','','hello']
list_tmp = list(my_list)
final_list = []
while '' in list_tmp:
idx = list_tmp.index('')
final_list.append(list_tmp[:idx])
list_tmp = list_tmp[idx + 1:]