I am trying to add list object to Dictionary.
Code:
for line in file:
splitObj=line.split("=") #split a line xxx= yyy using = delimiter
listObj=list(splitObj)
chip_mem.update(listObj[0], listObj[1])
This didn't help. Can anyone please let me know how to add the contents of the list to the dict as a key, value pair?
for line in file:
pieces = line.split("=")
chip_mem[pieces[0]] = pieces[1]
Note that there's no reason to call list() on the result of .split, since it's already a list.
Note that if not all of your lines have = signs in them, you might need to check for this:
for line in file:
pieces = line.split("=")
if len(pieces) > 1:
chip_mem[pieces[0]] = pieces[1]
Assuming you get a key and a value made for each thing in your list by splitting them on the equal sign, you can always do:
for k,v in list.split("="):
mydict[k] = v
dict update method requires other key-value pairs, see:
>>> mydict = {}
>>> mydict.update({'param': 'value'})
>>> print mydict # prints{'param': 'value'}
So in your case, for instance:
myfile = open("config.txt")
lines = myfile.readlines()
chip_mem = {}
for line in lines:
parts = line.strip().split("=")
chip_mem.update({parts[0]: parts[1]})
print chip_mem
Related
My file has something like this:
House Plant, 2, 5, 6
House Plant1, 4, 5, 7
... and so on
I want the two words to be as keys and the numbers as integers values and put all of the lines into a dictionary.
{'House Plant':[2,5,6],'House Plant1':[4,5,7], etc}
And this doesnt really work like that:
dictionary = {}
with open("persons.dat","r") as file:
for line in file:
items = line.split()
key, values = items[1], items[2:]
dictionary.setdefault(key,[]).extend(values)
print(items)
First you have to split the line based on ,.
items = line.split(',')
Also collections.defaultdict would be better choice to manage the list of items.
from collections import defaultdict
dictionary = defaultdict(list)
with open("persons.dat","r") as file:
for line in file:
items = line.split(',')
key, values = items[0], items[1:]
dictionary[key].extend(list(map(int, values)))
First of all split your string using ',' :
dictionary = {}
with open("persons.dat", "r") as file:
for line in file:
items = line.split(',')
dictionary[items[0]] = [int(x) for x in items[1:]]
print(dictionary)
I'm trying to make a function that reads through a protocol buffer and creates a dictionary with a list matched up to each key, like so:
Source:
{
name: "foo"
...
some_value: "a"
some_value: "b"
},
{
name: "bar"
...
some_value: "c"
some_value: "d"
}
Desired Output:
{'foo': ['a','b'], 'bar': ['c','d',]}
Here is my code:
import re
STATIC_SRC = '/path/to/my/file.txt'
def CountBrackets(line):
if '{' in line:
return 1
if '}' in line:
return -1
else:
return 0
with open(STATIC_SRC, 'r') as src_file:
bracket_count = 0
key = ''
values = []
my_dict = {}
for line in src_file:
line = line.strip()
bracket_count += CountBrackets(line)
# Finds line like 'name: "foo"' and stores 'foo' as key
if line.startswith('name:'):
key = re.findall('"([^"]*)"', line)
key = ''.join(key)
# Finds line like 'some_value: "a"' and adds 'a' to list
if line.startswith('some_value:'):
value = re.findall('"([^"]*)"', line)
values.append(value)
# When bracket count returns to 0, it's reached the end of a tupe
# and should store the current key and list.
if bracket_count == 0:
my_dict[key] = values
del values[:] # This is where I'm having issues.
print(role_dict)
My problem is that I can't get the list to successfully clear at the end of the tuple (in the source file). I have tried the following two methods, neither gave the correct output.
Method:
values = []
Result:
{'foo': ['a', 'b'], 'bar': ['a','b','c','d']}
Method:
del values[:]
Result:
{'foo': [], 'bar': []}
I've had it print all the keys/values as it loops and those are working as desired. It's also writing to the dictionary at the write time based on bracket count. It seems that the method I used for clearing somehow clears 'values' even after they've been added to the dictionary.
Can anyone shed some light on what's going wrong here and how to properly empty the list of values? Thanks!
EDIT: By request, tl;dr
I'd like the program to loop through this logic:
if x:
- store something to 'key'
if y:
- add something to a list 'values'
if z:
- write the current 'key' and 'values' to a dictionary
- clear the list 'values'
How do I clear the list of values at the end?
I don't know why you are getting that output on your first attempt. It worked for me. See below.
with open(STATIC_SRC, 'r') as src_file:
bracket_count = 0
key = ''
values = []
my_dict = {}
for line in src_file:
print(values)
line = line.strip()
bracket_count += CountBrackets(line)
# Finds line like 'name: "foo"' and stores 'foo' as key
if line.startswith('name:'):
key = re.findall('"([^"]*)"', line)
key = ''.join(key)
# Finds line like 'some_value: "a"' and adds 'a' to list
if line.startswith('some_value:'):
value = re.findall('"([^"]*)"', line)
values.extend(value) # append create a new list inside the existing list
# When bracket count returns to 0, it's reached the end of a tupe
# and should store the current key and list.
if bracket_count == 0:
my_dict[key] = values
values = []
print(my_dict) # the name of the dict was wrong
The result is
{'foo': ['a', 'b'], 'bar': ['c', 'd']}
I just edited the last print and replaced append with extend.
You cannot del values because that will delete the value in the dict, as it is the same object in memory.
d = {}
k = [1,2,3]
d['a'] = k
d
# {'a': [1, 2, 3]}
id(d['a']) == id(k)
# True
Running Python 2.7.6.
Today I need to replace the key of dict one by value of dict two. Dict one has multiple keys and I only want to replace the keys which match dict 2.
In the end I want to get the dict one back with the old keys (the ones which did not match) and the new keys (which have been changed when they matched)
I wrote the following script but I get no output so I am not sure if I am doing it right, can someone explain to me?
Thanks a lot
ERCC = {}
my_file = open('a.txt')
for line in my_file:
config,name = line.strip().split()
ERCC[contig] = name
RSEM = {}
names_file = open('b.txt')
for line in names_file:
genes, count = line.strip().split()
RSEM[gene] = count
def convert(RSEM,ERCC):
for key, value in RSEM.items():
for keys, values in ERCC.items():
if keys == key:
RSEM[key] = values
return RSEM
print RSEM
convert(RSEM, ERCC)
>>> dic={}
>>> for k,v in myboi.items():
r=input("Enter item to Update write in ""=")
if r:
dic[r]=v
else:
dic[k]=v
Enter item to Update write in ="Mahesh"
Enter item to Update write in ="Saka"
>>>
>>> dic
{'Mahesh': 'Mahesh', 'Saka': 'Mahesh'}
You want compulsary input key in this program you want update one or more time you empty dic={}
result={'Mahesh': 'Mahesh', 'Saka': 'Mahesh'}
>>> fi.close()
>>> fi=open("m.txt","r")
>>> fi.readlines()
['Maheshname']
>>> fi=open("m.txt","w+")
>>> for k,v in myboi.items():
fi.write("'"+k+"'"+":"+"'"+v+"'")
>>> fi.close()
>>> fi=open("m.txt","r")
>>> fi.readlines()
["'Mahesh':'Mahesh''name':'Mahesh'"]
Here's a two-liner for the convert function:
RSEM = {key: ERCC.get(key, RSEM[key]) for key in RSEM}
print RSEM
To dump a dict to a file just do:
with open("your_file_name", "w") as dumpfile:
dumpfile.write(str(RSEM))
Your code seems to be fine. But you have used return statement before print statement. The execution of convert function stops at return *** and the print statement is not executed at all. That is the reason why you are not getting any output.
I'm given a .tsv file called "population.tsv", which tells the populations of many cities. I have to create a dictionary with the cities being the key and the populations being its values. After creating the dictionary, I have to eliminate the cities which have less than 10,000 people. Whats wrong?
def Dictionary():
d={}
with open("population.tsv") as f:
for line in f:
(key, value)=line.split()
d[int(key)]=val
return {}
list=Dictionary()
print(list)
There are two issues with your program
It returns an empty dict {} instead of the dict you created
You have still not incorporated the filter function I have to eliminate the cities which have less than 10,000 people.
You shouldn't name a variable to a built-in
The fixed code
def Dictionary():
d={}
with open("population.tsv") as f:
for line in f:
(key, value)=line.split()
key = int(val)
#I have to eliminate the cities which have less than 10,000 people
if key < 10000:
d[int(key)]=val
#return {}
#You want to return the created dictionary
return d
#list=Dictionary()
# You do not wan't to name a variable to a built-in
lst = Dictionary()
print(lst)
Note you could also use the dict built-in by passing a generator expression or straightforward dict comprehension (If using Py 2.7)
def Dictionary():
with open("population.tsv") as f:
{k: v for k,v in (map(int, line.split()) for line in f) if k < 10000}
#If using Py < Py 2.7
#dict((k, v) for k,v in (map(int, line.split()) for line in f) if k < 10000)
I have a file with a list of paired entries (keys) that goes like this:
6416 2318
84665 88
90 2339
2624 5371
6118 6774
And I've got another file with the values to those keys:
266743 Q8IUM7
64343 H7BXU6
64343 Q9H6S1
64343 C9JB40
23301 Q8NDI1
23301 A8K930
As you can see the same key can have more than one value. What I'm trying to do is creating a dictionary by automatically creating the initial k, v pair, and then append more values for each entry that is already in the dictionary, like this:
Program finds "266743: 'Q8IUM7'", then "64343: 'H7BXU6'". And when it finds "64343: 'Q9H6S1'" it does this: "64343: ['H7BXU6', 'Q9H6S1']".
This is what I have so far:
# Create dictionary
data = {}
for line in inmap:
value = []
k, v = [x.strip() for x in line.split('\t')]
data[k] = value.append(v)
if k in data.viewkeys() == True and v in data.viewvalues() == False:
data[k] = value.append(v)
But the if statement seems to not be working. That or having the value = [] inside the for loop. Any thoughts?
This is not a good idea. You should be using a list from the start and expand that list as you go along, not change from "string" to "list of strings" when more than one value is found for the key.
For this, you can simply use
from collections import defaultdict
data = defaultdict(list)
for line in inmap:
k, v = (x.strip() for x in line.split('\t'))
data[k].append(v)
This works because a defaultdict of type list will automatically create a key together with an empty list as its value when you try to reference a key that doesn't yet exist. Otherwise, it behaves just like a normal dictionary.
Result:
>>> data
defaultdict(<type 'list'>, {'23301': ['Q8NDI1', 'A8K930'],
'64343': ['H7BXU6', 'Q9H6S1', 'C9JB40'], '266743': ['Q8IUM7']})