Convert list elements to list values of another list - python-3.x

I am trying to convert list elements of a given list to list value of another list. Here is an example:
list1 = ['apple', 'tomato', 'milk', 'beans', 'mango']
list2 = [{0,4}, {1,3}, 2]
result = []
expected output:
[{'apple', 'banana'}, {'tomato', 'beans'}, 'milk']
I am trying to use the below code, but it does not work:
for i in list2:
result.append(list1[i])

Assuming list2 will only contain set, list, or int. This would be my approach.
list1 = ['apple', 'tomato', 'milk', 'beans', 'mango']
list2 = [{0,4}, {1,3}, 2]
result = []
# [{'apple', 'banana'}, {'tomato', 'beans'}, 'milk']
for x in list2:
temp_lst = []
if type(x) in [set, list]:
new_set = set()
for y in x:
new_set.add(list1[y])
temp_lst.append(new_set)
else:
temp_lst.append(list1[x])
result.extend(temp_lst)
print(result)

Related

The problem of using {}.fromkey(['k1','k2'],[]) and {'k1':[],'k2':[]}

list1 = [99,55]
dict1 = {'k1':[],'k2':[]}
for num in list1:
if num > 77:
dict1['k1'].append(num)
else:
dict1['k2'].append(num)
print(dict1)
{'k1':[99],'k2':[55]}
But when I replaced dict1 = {'k1':[],'k2':[]} to {}.fromkeys(['k1','k2'],[]) , the result became {'k1': [99, 55], 'k2': [99, 55]}
why this happens? I really have no idea.
This happens because you are passing the same list object to both keys. This is the same situation as when you create an alias for a variable:
a = []
b = a
a.append(55)
b.append(99)
print(b)
prints [55, 99] because it is the same list instance.
If you want to make it more concise from a list of keys to initialize with empty list, you can do this:
dict1 = {k: [] for k in ('k1', 'k2')}
This will create a new list instance for every key.
Alternatively, you can use defaultdict
from collections import defaultdict
list1 = [99,55]
dict1 = defaultdict(list)
for num in list1:
if num > 77:
dict1['k1'].append(num)
else:
dict1['k2'].append(num)
print(dict1)
Also works.
The fromKeys() can also be supplied with a mutable object as the default value.
if we append value in the original list, the append takes place in all the values of keys.
example:
list1 = ['a', 'b', 'c', 'd']
list2 = ['SALIO']
dict1 = dict.fromkeys(list1, list2)
print(dict1)
output:
{'a': ['SALIO'], 'b': ['SALIO'], 'c': ['SALIO'], 'd': ['SALIO']}
then you can use this:
list1 = ['k1', 'k2']
dict1 = {'k1':[],'k2':[]}
list2 =[99,55]
for num in list2:
if num > 77:
a = ['k1']
dict1 = dict.fromkeys(a, [num])
else:
b = ['k2']
dict2 = dict.fromkeys(b,[num] )
res = {**dict1, **dict2}
print(res)
output:
{'k1': [99], 'k2': [55]}
You can also use the python code to merge dict code:
this function:
def Merge(dict1, dict2):
return(dict2.update(dict1))
then:
print(Merge(dict1, dict2)) #This return None
print(dict2) # changes made in dict2

Printing list containing a string

I am trying to store a string variable containg some names, I want to store the respective variable in a list and print it, but am unable print the values which are stored in variable.
name='vsb','siva','anand','soubhik' #variable containg some names
lis=['name'] # storing the variable in a list
for x in lis:
print(x) #printing the list using loops
Image:
Maybe dictionary? Try this
variable_1 = "aa"
variable_2 = "bb"
lis = {}
lis['name1'] = variable_1
lis['name2'] = variable_2
for i in lis:
print(i)
print(lis[i])
Your name variable is actually a tuple.
Example of tuple declaration:
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
Example of list declaration:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
For a better understanding you should read The Python Standard Library or do a tutorial.
For your problem maybe the dictionary is the solution:
# A tuple is a sequence of immutable Python objects
name='vsb','siva','anand','soubhik'
print('Tuple: ' + str(name)) # ('vsb', 'siva', 'anand', 'soubhik')
# This is a list containing one element: 'name'
lis=['name']
print('List: ' + str(lis)) # ['name']
# Dictionry with key 'name' and vlue ('vsb','siva','anand','soubhik')
dictionary={'name':name}
print('Dictionary: ' + str(dictionary))
print('Dictionary elements:')
print(dictionary['name'])
print('Tuple elements:')
for x in name:
print(x)
print('List elements:')
for x in lis:
print(x)
Output
Tuple: ('vsb', 'siva', 'anand', 'soubhik')
List: ['name']
Dictionary: {'name': ('vsb', 'siva', 'anand', 'soubhik')}
Dictionary elements:
('vsb', 'siva', 'anand', 'soubhik')
Tuple elements:
vsb
siva
anand
soubhik
List elements:
name

return dictionary of file names as keys and word lists with words unique to file as values

I am trying to write a function to extract only words unique to each key and list them in a dictionary output like {"key1": "unique words", "key2": "unique words", ... }. I start out with a dictionary. To test with I created a simple dictionary:
d = {1:["one", "two", "three"], 2:["two", "four",
"five"], 3:["one","four", "six"]}
My output should be:
{1:"three",
2:"five",
3:"six"}
I am thinking maybe split in to separate lists
def return_unique(dct):
Klist = list(dct.keys())
Vlist = list(dct.values())
aList = []
for i in range(len(Vlist)):
for j in Vlist[i]:
if
What I'm stuck on is how do I tell Python to do this: if Vlist[i][j] is not in the rest of Vlist then aList.append(Vlist[i][j]).
Thank you.
You can try something like this:
def return_unique(data):
all_values = []
for i in data.values(): # Get all values
all_values = all_values + i
unique_values = set([x for x in all_values if all_values.count(x) == 1]) # Values which are not duplicated
for key, value in data.items(): # For Python 3.x ( For Python 2.x -> data.iteritems())
for item in value: # Comparing values of two lists
for item1 in unique_values:
if item == item1:
data[key] = item
return data
d = {1:["one", "two", "three"], 2:["two", "four", "five"], 3:["one","four", "six"]}
print (return_unique(d))
result >> {1: 'three', 2: 'five', 3: 'six'}
Since a key may have more than one unique word associated with it, it makes sense for the values in the new dictionary to be a container type object to hold the unique words.
The set difference operator returns the difference between 2 sets:
>>> a = set([1, 2, 3])
>>> b = set([2, 4, 6])
>>> a - b
{1, 3}
We can use this to get the values unique to each key. Packaging these into a simple function yields:
def unique_words_dict(data):
res = {}
values = []
for k in data:
for g in data:
if g != k:
values += data[g]
res[k] = set(data[k]) - set(values)
values = []
return res
>>> d = {1:["one", "two", "three"],
2:["two", "four", "five"],
3:["one","four", "six"]}
>>> unique_words_dict(d)
{1: {'three'}, 2: {'five'}, 3: {'six'}}
If you only had to do this once, then you might be interested in the less efficeint but more consice dictionary comprehension:
>>> from functools import reduce
>>> {k: set(d[k]) - set(reduce(lambda a, b: a+b, [d[g] for g in d if g!=k], [])) for k in d}
{1: {'three'}, 2: {'five'}, 3: {'six'}}

Inserting list into another list using loops only:

I'm using the current version of python. I need to return a copy of list1 with list2 inserted at the position indicated by index i.e if the index value is 2, list2 is inserted into list 1 at position 2. I can only use for/while loops, the range function & the list_name.append (value) methods and the lists cannot be sliced. So if list1 list1 = boom list2 = red and the index value = 2, how do I return a new list = boredom? I have this so far:
list1 = ['b','o','o','m']
list2 = ['r','e','d']
index = 2
new_list = []
if index > len(list1):
new_list = list1 + list2
print (new_list)
if index <= 0:
new_list = list2 + list1
print (new_list)
An alternative approach to Padriac's - using three for loops:
list1 = ['b','o','o','m']
list2 = ['r','e','d']
n = 2
new_list = []
for i in range(n): # append list1 until insert point
new_list.append(list1[i])
for i in list2: # append all of list2
new_list.append(i)
for i in range(n, len(list1)): # append the remainder of list1
new_list.append(list1[i])
Once you hit the index, use an inner loop to append each element from list2:
for ind, ele in enumerate(list1):
# we are at the index'th element in list1 so start adding all
# elements from list2
if ind == index:
for ele2 in list2:
new_list.append(ele2)
# make sure to always append list1 elements too
new_list.append(ele)
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
If you must use range just replace enumerate with range:
new_list = []
for ind in range(len(list1)):
if ind == index:
for ele2 in list2:
new_list.append(ele2)
new_list.append(list1[ind])
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
Or without ifs using extend and remove if allowed:
new_list = []
for i in range(index):
new_list.append(list1[i])
list1.remove(list1[i])
new_list.extend(list2)
new_list.extend(list1)
Appending as soon as we hit the index means the elements will be inserted from the correct index, the elements from list1 must always be appended after your if check.
Check out this small snippet of code I've written.
Check the while condition that is used. I hope it will answer your question.
email = ("rishavmani.bhurtel#gmail.com")
email_split = list(email)
email_len = len(email)
email_uname_len = email_len - 10
email_uname = []
a = 0
while (a < email_uname_len):
email_uname[a:email_uname_len] = email_split[a:email_uname_len]
a = a + 1
uname = ''.join(email_uname)
uname = uname.replace(".", " ")
print("Possible User's Name can be = %s " %(uname))

Pulling a field from a list based on second list

I have the following lists:
list1 = [["value1":"name1", "value2":"check1"], ["value1":"name2", "value2":" check2"],
["value1":"name3", "value2":" check3"]]
list2 = ['name1', 'name2']
I would like to pull the list of all the "value2" for name1 and name2.
as:
[check1, check2]
This should do it:
def list3 = list1.findAll { it.value1 in list2 }.value2
def list1 = [["value1":"name1", "value2":"check1"], ["value1":"name2", "value2":" check2"],
["value1":"name3", "value2":" check3"]]
def list2 =list1.collect{it."value2"}

Resources