I dont know how to descibe it properly but this is what I want to achieve:
import yaml
list = {"test1":1,"test2":2,"test3":3}
print(yaml.dump(list, sort_keys=False, default_flow_style=False))
#Output
# test1: 1
# test2: 2
# test3: 3
# Update somehow
print(yaml.dump(list, sort_keys=False, default_flow_style=False))
#Output
# <#test1>: 1
# <#test2>: 2
# <#test3>: 3
Use a comprehension to transform your keys:
# list is not a list but a dict and don't use builtin names
data = {"test1":1,"test2":2,"test3":3}
# transform your keys
data = {f'<#{k}>': v for k, v in data.items()}
# export your data as usual
print(yaml.dump(data, sort_keys=False, default_flow_style=False)
Output:
<#test1>: 1
<#test2>: 2
<#test3>: 3
Related
Assuming a following text file (dict.txt) has
1 2 3
aaa bbb ccc
the dictionary should be {1: aaa, 2: bbb, 3: ccc} like this
I did:
d = {}
with open("dict.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
print (d)
but it didn't work. I think it is because of the structure of txt file.
The data which you want to be keys are in first line, and all the data which you want to be as values are in second line.
So, do something like this:
with open(r"dict.txt") as f: data = f.readlines() # Read 'list' of all lines
keys = list(map(int, data[0].split())) # Data from first line
values = data[1].split() # Data from second line
d = dict(zip(keys, values)) # Zip them and make dictionary
print(d) # {1: 'aaa', 2: 'bbb', 3: 'ccc'}
Updated answer based on OP edit:
#Initialize dict
d = {}
#Read in file by newline splits & ignore blank lines
fobj = open("dict.txt","r")
lines = fobj.read().split("\n")
lines = [l for l in line if not l.strip() == ""]
fobj.close()
#Get first line (keys)
key_list = lines[0].split()
#Convert keys to integers
key_list = list(map(int,key_list))
#Get second line (values)
val_list = lines[1].split()
#Store in dict going through zipped lists
for k,v in zip(key_list,val_list):
d[k] = v
First create separate list for keys and values, with condition
like :
if (idx % 2) == 0:
keys = line.split()
values = lines[idx + 1].split()
then combine both the lists
d = {}
# Get all lines in list
with open("dict.txt") as f:
lines = f.readlines()
for idx, line in enumerate(lines):
if (idx % 2) == 0:
# Get the key list
keys = line.split()
# Get the value list
values = lines[idx + 1].split()
# Combine both the lists in dictionary
d.update({ keys[i] : values[i] for i in range(len(keys))})
print (d)
I've a dictionary dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
I want it to be saved it in the text file output.txt with the specified format
1 2 3 (3)
2 3 4 (2)
3 4 8 (5)
modify the following code for this task
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
file.write(str(dic))
Iterate the dictionary and write content to text file.
Ex:
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
for k, v in dic.items(): #Iterate dic
file.write("{} ({}) \n".format(" ".join(map(str, k)), v)) #write to file.
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
for k, v in dic.items(): #Iterate dic
file.write("{} ({}) \n".format(k, v)) #write to file.
Here we just have to pass the key and value to the format function. I dont think any other operations has to be done on this.
str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method allows to concatenate elements within a string through positional formatting.
I want to write a python script that is extracting certain conditions which is as follows:
a a1 1
2
3
a2 0
1
b b1 1
2
b2 0
3
Until now what I was able to do is create a dictionary of first 2 columns and then create another dictionary for the 2nd and 3rd column. But I want all the 3 columns in one dictionary.
Here is the pseudo code that I have written so far:
mydict = {}
for lines in f:
if 'a' or 'b' in lines:
key = a
if 'a1' in lines:
value = a1
mydict.setdefault(key, []).append(value)
and something similar for the second dictionary as well.
Please help me out !
expected output:
{ 'a' : [ 'a1': [1,2,3]],'b':['b1': [0,1]}
As I mentioned earlier, I want to create this dictionary from 2 existent dictionaries which look something like this
{'a': a1, 'b':b1} #First Dictionary
{'a1': [1,2,3], 'b1': 123} #Second Dictionary
I created these 2 dictionaries from a text file. And the code that is posted, is the code of how I extracted these 2 dictionaries.
not the sexiest code on earth i admit
mydict = {}
for line in data.split('\n'):
if not line:
continue
line = line.split()
if len(line) == 3:
l1_key = line.pop(0)
mydict[l1_key] = {}
if len(line) == 2:
l2_key = line.pop(0)
mydict[l1_key][l2_key] = []
mydict[l1_key][l2_key].append(line.pop(0))
print(mydict)
In Python 2.7, how does one dynamically access and print out the keys and values of a nested dictionary? Here's a nonsensical example: https://jsoneditoronline.org/?id=da7a486dc2e24bf8b94add9f04c71b4d
Normally, I would do something like:
import json
json_sample = 'sample_dict.json'
json_file = open(json_sample, 'r')
json_data = json.load(json_file)
items = json_data['sample_dict']
for item in items:
dict_id = item['dict_id']
person = item['person']['person_id']
family = item['family']['members']
print dict_id
print person
print family
I can hard code it like this and it'll give me desirable results, but how would I access each of the keys and values dynamically so that:
The first row just prints the keys (dict_id, person['person_id'], person['name'], family['members']['father'])
The second row prints the values respectively (5, 15, "Martin", "Jose")
The end result should be in a CSV file.
You can use a recursive visitor/generator which returns all the path/value pairs of the leaves:
def visit_dict(d, path=[]):
for k, v in d.items():
if not isinstance(v, dict):
yield path + [k], v
else:
yield from visit_dict(v, path + [k])
(replace the yield from ... with the appropriate equivalent if using Python < 3.4)
Getting the keys:
>>> ','.join('/'.join(k) for k, v in visit_dict(json_data['sample_dict'][0]))
'dict_id,person/person_id,person/name,person/age,family/person_id,family/members/father,family/members/mother,family/members/son,family/family_id,items_id,furniture/type,furniture/color,furniture/size,furniture/purchases'
and the values:
>>> ','.join(str(v) for k, v in visit_dict(json_data['sample_dict'][0]))
'5,15,Martin,18,20,Jose,Maddie,Jerry,2,None,Chair,Brown,Large,[]'
I'm running python 2.7 in PS on a w10. I want to print the key and the value of a dictionary with every pair enumerated.
I do the following:
my_dict = {'key_one': 1, 'key_two': 2, 'key_three': 3}
for k, v in enumerate(my_dict.iteritems(), start = 1):
print k, v
which in turn gives:
1 ('key_one', 1)
2 ('key_two', 2)
3 ('key_three', 3)
How do I return the entries without the braces?
Example - I want to put a = sign in between my key-value pairs.
If you want to keep the indicies (from enumerate), then you're going to have to unpack the key and value from the dict items separates. Right now what you're calling k is actually an index, and what you're calling v is actually a key-value pair. Try something like this:
for i, (k, v) in enumerate(my_dict.iteritems(), start=1):
print i, k, v
That results in something like:
1 key_two 2
2 key_one 1
3 key_three 3
To get them formatted with an equals sign, you'd have to change the print statement to print i, "{}={}".format(k, v), which would result in something like:
1 key_two=2
2 key_one=1
3 key_three=3
If you need to retrieve the keys in a consistent order, use sorted(), like this:
for i, (k, v) in enumerate(sorted(my_dict.iteritems()), start=1):
...
Or, if you want to sort by values first instead of the keys first, you could specify a key function for the sorted() call. That would look like: sorted(my_dict.iteritems(), key=lambda (x, y): (y, x)). That would give you an output of
1 key_one=1
2 key_two=2
3 key_three=3
You don't need enumerate if you just want to print the existing key and values in your dictionary. Just use format():
for k, v in my_dict.items():
print '{} = {}'.format(k, v)
This would give:
key_one = 1
key_two = 2
key_three = 3
This works
my_dict = {'key_one': 1, 'key_two': 2, 'key_three': 3}
for key,value in my_dict.iteritems():
print key,value
Like this?
>>> for k, v in my_dict.iteritems():
... print k, v
...
key_two 2
key_one 1
key_three 3
or
>>> for i, (k, v) in enumerate(my_dict.iteritems(), start=1):
... print i, k, v
...
1 key_two 2
2 key_one 1
3 key_three 3
Simple one-line solution(for Python 2.7):
print '\n'.join([k+'='+ str(my_dict[k]) for k in my_dict.keys()])
The output:
key_two=2
key_one=1
key_three=3
You do not need enumerate() here. It is used when you need to iterate along with the index. you do not even need str.format() for achieving this. Simply place a entry of '=' string between your key, value and you will get what your desire. For example:
>>> my_dict = {'key_one': 1, 'key_two': 2, 'key_three': 3}
>>> for key, value in my_dict.items():
... print key, '=', value
...
key_two = 2
key_one = 1
key_three = 3
Edit: Based on the comment at user3030010's answer
Note: dict in python are un ordered. In case you want to maintain the order, use collections.OrderedDict() instead. It will preserve the order independent of the platform and python version. For example if you created the dict like:
>>> from collections import OrderedDict
>>> my_dict = OrderedDict()
>>> my_dict['key_one'] = 1
>>> my_dict['key_two'] = 2
>>> my_dict['key_three'] = 3
On iterating it, you will always get the same response as:
>>> for key, value in my_dict.items():
... print key, '=', value
...
key_one = 1
key_two = 2
key_three = 3