I am given a .txt file which looks like this..
2:rain
3:odd
5:yes
6:go
I need to convert it into a dictionary.
This is what I have done so far.
words_dict = {}
file = open(filename, "r")
for word in file:
k, v = word.split(":")
words_dict[k.strip()] = v.strip()
file.close()
return words_dict
However, when i go and print the dictionary it does not match my expected output of {2: 'rain', 3: 'odd', 5: 'yes', 6: 'go'}
l="2:rain 3:odd 5:yes 6:go".split()
{x.split(":")[0]:x.split(":")[1] for x in l}
list_ = [x for x in open('text.txt').read().split()]
dict_ = {k: v for k, v in [x.split(':') for x in list_]}
# list_ = ['2:rain', '3:odd', '5:yes', '6:go']
# dict_ = {'2': 'rain', '3': 'odd', '5': 'yes', '6': 'go'}
Related
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
I have a text file that have a pattern like
#
a,b
c,d
#
e,f
g,h
I want the result to print as each block separated is an element and each line in the block is a sub-element to the block one
[[[a, b], [c, d]], [[e, f], [g, h]]]
Here is my code, any suggestion from here to get the result ? Thanks
ret_list = []
a = open(file_name,'r')
content = a.read()
content = content.split('#')
for l in content:
l = l.strip().split('\n')
for elem in l:
temp = []
elem = elem.split(',')
if '' not in elem:
temp.append(elem)
ret_list.append(temp)
a.close()
And the result I got
[[], [['a', 'b']], [['c', 'd']], [['e', 'f']], [['g', 'h']]]
You're creating temp = [] for every line - but you want to create it for every "block" - so you move it outside of the inner for loop. (same for the ret_list.append())
content = content.split('#')
for l in content:
l = l.strip().split('\n')
temp = []
for elem in l:
elem = elem.split(',')
if '' not in elem:
temp.append(elem)
ret_list.append(temp)
This gives you
[[], [['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]
You could add a check that temp is not empty before appending.
if temp:
ret_list.append(temp)
Another way to avoid the leading empty "block" is to strip before splitting
content.strip('#').split('#')
Finally, this is how I would write it.
ret_list = []
for block in content.strip('#').split('#'):
lines = block.strip().splitlines()
lines = [ line.split(',') for line in lines ]
ret_list.append(lines)
for l in content:
l = l.strip().split('\n')
k=[]
for elem in l:
temp=[]
elem = elem.split(',')
if '' not in elem:
temp.append(elem)
k=k+temp
if k!=[]:
ret_list.append (k)
print (ret_list)
i created new list k to store a block with two block i.e [['a', 'b'], ['c', 'd']] and then added to ret_list if k list is not empty
output
[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]
I have an input.txt file like below format.
A = Xyz
B
Value:274:53:3
C = 1190
E
WQQQW
Value:554
A = UrR
B
Value:113:00:1
C = 34
E
WQQQW
Value:982
I'd like to store in a dictionary the data related with A, B and E in order to get:
d = {
'A': ['Xyz', 'UrR'],
'B': ['274:53:3', '113:00:1'],
'E': ['554', '982'],
}
I'm doing like below, not I only storing the key, value pair related with A since the values for A are in the same line.
d = {"A":[],"B":[],"E":[]}
for line in open('input.txt'):
lst_line = line.replace(":", "=", 1).split("=")
if ("A" or "B" or "E") in lst_line[0]:
k = lst_line[0].strip()
v = lst_line[1].replace("\n", "").strip()
d[k].append(v)
>>> d
{'A': ['Xyz', 'UrR'], 'B': [], 'E': []}
I'm stuck in how to store the values for B that is one line below after Value: and for E that is 2 lines below after Value:.
Every key seems to have a very specific logic which can be divided into independent if conditions. Below code reads value for respective key based on the condition mentioned in question.
d = {"A": [], "B": [], "E": []}
with open("input.txt") as file:
while True:
line = file.readline() # read next line
if not line:
break # break on end of file
lst_line = line.replace(":", "=", 1).split("=") # key from line
if "A" in lst_line[0]:
k = lst_line[0].strip()
v = lst_line[1].replace("\n", "").strip()
d[k].append(v)
if "B" in lst_line[0]:
k = lst_line[0].strip()
line = file.readline() # read next line for value i.e. if key is B value is on the next line (one line below)
lst_line = line.replace(":", "=", 1).split("=") # get value for B
v = lst_line[1].replace("\n", "").strip()
d[k].append(v)
if "E" in lst_line[0]:
k = lst_line[0].strip()
file.readline() # skip junk line
line = file.readline() # read next line for value i.e. for E value is two lines below.
lst_line = line.replace(":", "=", 1).split("=") # get value for E
v = lst_line[1].replace("\n", "").strip()
d[k].append(v)
print(d)
Output:
{'A': ['Xyz', 'UrR'], 'B': ['274:53:3', '113:00:1'], 'E': ['554', '982']}
Here is how you can use regex:
import re
with open('file.txt', 'r') as r:
r = r.read()
dct = {'A': re.findall('(?<=A \= ).*?(?= \n)',r),
'B': re.findall('\d\d\d:\d\d:\d',r),
'E': re.findall('(?<=Value:)\d\d\d(?!:)',r)}
print(dct)
Output:
{'A': ['Xyz', 'UrR'],
'B': ['274:53:3', '113:00:1'],
'E': ['554', '982']}
Basically, I am trying to extract the values from one dictionary and update the value in another dictionary. I have four lists as follows:
a = [1,1,2,3,4,5]
b = [0,3,0,5,6,0]
c = [2,3,4,5,6,5]
d = [20,30,40,50,60,70]
So I use a defaultdict to store key,value pairs for a,b like:
one = defaultdict(list)
for k, v in zip(a, b):
one[k].append(v)
two = defaultdict(list)
for k, v in zip(c, d):
two[k].append(v)
Essentially, b is linked to c so I am trying to extract the values in the two dictionary and then update
the values in the one dictionary
So in the end one would look like {1: 30, 3: 50, 4: 60}
This is my code:
three = defaultdict(list)
for k, v in one.items():
if v in two.keys():
newvalue = two[v].values()
three[k].append(newvalue)
But I am now getting an error at line if v in two.keys(): as unhashable type: 'list'. I'm so lost, all
I want to do is use the values from one dictionary and then use those values to find the keys (which are the values
from the other table) and then get those corressponding values.
You are creating a dictionary of list in the beginning:
one = defaultdict(list)
for k, v in zip(a, b):
one[k].append(v)
[output] : defaultdict(list, {1: [0, 3], 2: [0], 3: [5], 4: [6], 5: [0]})
two = defaultdict(list)
for k, v in zip(c, d):
two[k].append(v)
[output] : defaultdict(list, {2: [20], 3: [30], 4: [40], 5: [50, 70], 6: [60]})
Therefore when calling k,v in one.items(), you are getting a key and a list.
Simply switch to iterate through the list , and you should be good to go
three = defaultdict(list)
for k, v in one.items():
for value in v:
if value in two.keys():
newvalue = two[value]
three[k].append(newvalue)
However I'm getting this output :
defaultdict(list, {1: [[30]], 3: [[50, 70]], 4: [[60]]})
Which sounds reasonable to me, but it is not your expected one, can you please explain ?
Let's try know with dic comprehension
output = { k : two[v_2] for k,v in one.items() for v_2 in v}
[output] : {1: [30], 2: [], 3: [50, 70], 4: [60], 5: []}
Request to sum :
Of course, multiple ways of doing it , the quickest is again with dict_comprehension and sum
output_sum = {k: sum(v) for k,v in output.items()}
How can I print a nested python dictionary in a specific format?
So, my dictionary is looks like this:
dictionary = {'Doc1':{word1: 3, word2: 1}, 'Doc2':{word1: 1, word2: 14, word3: 3}, 'Doc3':{word1: 2}}
I tried the following way:
for x, y in dictionary.items():
print(x,":", y)
But it will printL`
Doc1: {word1:3, word2: 1}
Doc2: {word1:1, word2:14, word3:3}
Doc3: {word1:2}
How to get rid of the bracket and print the plain information?
I want to print on the following format:
Doc1: word1:3; word2:1
Doc2: word1:1; word2:14; word3: 3
Doc3: word1:2;
:
in your case 'y' is a dict, so if you want to print it differently you can override the repr (representation of the object) or dict.
alternatively you can use some recursion here
def print_d(dd):
if type(dd) != dict:
return str(dd)
else:
res = []
for x,y in dd.items():
res.append(''.join((str(x),':',print_d(y))))
return '; '.join(res)
if __name__=='__main__':
dictionary = {'Doc1':{'word1': 3, 'word2': 1}, 'Doc2':{'word1': 1, 'word2': 14, 'word3': 3}, 'Doc3':{'word1': 2}}
for x, y in dictionary.items():
print(x,": ", print_d(y))
Aside from the fact that your original dictionary declaration is not valid python unless each word is a defined variable, this seems to work:
import json
print(json.dumps(dictionary).replace("{","").replace(',','').replace("}","\n").replace('"',''))
Result:
Doc1: word1: 3 word2: 1
Doc2: word1: 1 word2: 14 word3: 3
Doc3: word1: 2